Ajax介绍和使用教程 1.Ajax简介
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
AJAX 不需要任何浏览器插件,但需要用户允许 JavaScript 在浏览器上执行。
XMLHttpRequest 只是实现 Ajax 的一种方式,当然也可以使用 fetch API 等现代方法。
2.Ajax的应用
运用 XHTML+CSS 来表达资讯;
运用 JavaScript 操作 DOM(Document Object Model)来执行动态效果;
运用 XML 和 XSLT 操作资料;
运用 XMLHttpRequest 或新的 Fetch API 与网页服务器进行异步资料交换;
注意: AJAX 与 Flash、Silverlight 和 Java Applet 等 RIA 技术是有区分的。
3.Ajax简单使用教程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 <!DOCTYPE html > <html > <head > <meta charset ="utf-8" > <script > function loadXMLDoc ( ) { var xmlhttp; if (window .XMLHttpRequest ) { xmlhttp = new XMLHttpRequest (); } else { xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP" ); } xmlhttp.open ("GET" , "https://api.example.com/data" , true ); header : 规定头的名称 value : 规定头的值 xmlhttp.onreadystatechange = function ( ) { if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) { console .log ("请求成功!!!!" ); } else { console .log ("请求失败......" ); } } xmlhttp.onerror = function ( ) { console .error ("网络请求错误 X " ); } xmlhttp.send (); } </script > </head > <body > <div id ="myDiv" > <h2 > 使用 AJAX 修改该文本内容</h2 > </div > <button type ="button" onclick ="loadXMLDoc()" > 修改内容</button > </body > </html >
4.关于AJAX 的onreadystatechange 请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性中存有 XMLHttpRequest 的状态信息。
属性
描述
onreadystatechange
存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。0: 请求未初始化1: 服务器连接已建立2: 请求已接收3: 请求处理中4: 请求已完成,且响应已就绪
status
200: “OK” 404: 未找到页面
1 2 3 4 5 6 7 xmlhttp.onreadystatechange =function ( ) { if (xmlhttp.readyState ==4 && xmlhttp.status ==200 ) { document .getElementById ("myDiv" ).innerHTML =xmlhttp.responseText ; } }
使用回调函数:进行简单的封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <!DOCTYPE html > <html > <head > <script > var xmlhttp;function loadXMLDoc (url,cfunc ){ if (window .XMLHttpRequest ) { xmlhttp=new XMLHttpRequest (); } else { xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP" ); } xmlhttp.onreadystatechange =cfunc; xmlhttp.open ("GET" ,url,true ); xmlhttp.send (); } function myFunction ( ){ loadXMLDoc ("/try/ajax/ajax_info.txt" ,function ( ) { if (xmlhttp.readyState ==4 && xmlhttp.status ==200 ) { document .getElementById ("myDiv" ).innerHTML =xmlhttp.responseText ; } }); } </script > </head > <body > <div id ="myDiv" > <h2 > 使用 AJAX 修改文本内容</h2 > </div > <button type ="button" onclick ="myFunction()" > 修改内容</button > </body > </html >
5.模拟真实请求以及ASP/PHP示例 (1)模拟真实请求 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <!DOCTYPE html > <html > <head > <meta charset ="utf-8" > <script > function showHint (str ){ var xmlhttp; if (str.length ==0 ) { document .getElementById ("txtHint" ).innerHTML ="" ; return ; } if (window .XMLHttpRequest ) { xmlhttp=new XMLHttpRequest (); } else { xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP" ); } xmlhttp.onreadystatechange =function ( ) { if (xmlhttp.readyState ==4 && xmlhttp.status ==200 ) { document .getElementById ("txtHint" ).innerHTML =xmlhttp.responseText ; } } xmlhttp.open ("GET" ,"/try/ajax/gethint.php?q=" +str,true ); xmlhttp.send (); } </script > </head > <body > <h3 > 在输入框中尝试输入字母 a:</h3 > <form action ="" > 输入姓名: <input type ="text" id ="txt1" onkeyup ="showHint(this.value)" /> </form > <p > 提示信息: <span id ="txtHint" > </span > </p > </body > </html >
(2)ASP服务器页面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 <% response.expires=-1 dim a(30) 'Fill up array with names a(1)="Anna" a(2)="Brittany" a(3)="Cinderella" a(4)="Diana" a(5)="Eva" a(6)="Fiona" a(7)="Gunda" a(8)="Hege" a(9)="Inga" a(10)="Johanna" a(11)="Kitty" a(12)="Linda" a(13)="Nina" a(14)="Ophelia" a(15)="Petunia" a(16)="Amanda" a(17)="Raquel" a(18)="Cindy" a(19)="Doris" a(20)="Eve" a(21)="Evita" a(22)="Sunniva" a(23)="Tove" a(24)="Unni" a(25)="Violet" a(26)="Liza" a(27)="Elizabeth" a(28)="Ellen" a(29)="Wenche" a(30)="Vicky" 'get the q parameter from URL q=ucase(request.querystring("q")) 'lookup all hints from array if length of q>0 if len(q)>0 then hint="" for i=1 to 30 if q=ucase(mid(a(i),1,len(q))) then if hint="" then hint=a(i) else hint=hint & " , " & a(i) end if end if next end if 'Output "no suggestion" if no hint were found 'or output the correct values if hint="" then response.write("no suggestion") else response.write(hint) end if %>
(3)php文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 <?php $a []="Anna" ;$a []="Brittany" ;$a []="Cinderella" ;$a []="Diana" ;$a []="Eva" ;$a []="Fiona" ;$a []="Gunda" ;$a []="Hege" ;$a []="Inga" ;$a []="Johanna" ;$a []="Kitty" ;$a []="Linda" ;$a []="Nina" ;$a []="Ophelia" ;$a []="Petunia" ;$a []="Amanda" ;$a []="Raquel" ;$a []="Cindy" ;$a []="Doris" ;$a []="Eve" ;$a []="Evita" ;$a []="Sunniva" ;$a []="Tove" ;$a []="Unni" ;$a []="Violet" ;$a []="Liza" ;$a []="Elizabeth" ;$a []="Ellen" ;$a []="Wenche" ;$a []="Vicky" ;$q =$_GET ["q" ];if (strlen ($q ) > 0 ){ $hint ="" ; for ($i =0 ; $i <count ($a ); $i ++) { if (strtolower ($q )==strtolower (substr ($a [$i ],0 ,strlen ($q )))) { if ($hint =="" ) { $hint =$a [$i ]; } else { $hint =$hint ." , " .$a [$i ]; } } } } if ($hint == "" ){ $response ="no suggestion" ; } else { $response =$hint ; } echo $response ;?>
6.XHR请求状态头速查 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 100——客户必须继续发出请求 101——客户要求服务器根据请求转换HTTP协议版本 200——交易成功 201——提示知道新文件的URL 202——接受和处理、但处理未完成 203——返回信息不确定或不完整 204——请求收到,但返回信息为空 205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件 206——服务器已经完成了部分用户的GET请求 300——请求的资源可在多处得到 301——删除请求数据 302——在其他地址发现了请求数据 303——建议客户访问其他URL或访问方式 304——客户端已经执行了GET,但文件未变化 305——请求的资源必须从服务器指定的地址得到 306——前一版本HTTP中使用的代码,现行版本中不再使用 307——申明请求的资源临时性删除 400——错误请求,如语法错误 401——请求授权失败 402——保留有效ChargeTo头响应 403——请求不允许 404——没有发现文件、查询或URl 405——用户在Request-Line字段定义的方法不允许 406——根据用户发送的Accept拖,请求资源不可访问 407——类似401,用户必须首先在代理服务器上得到授权 408——客户端没有在用户指定的饿时间内完成请求 409——对当前资源状态,请求不能完成 410——服务器上不再有此资源且无进一步的参考地址 411——服务器拒绝用户定义的Content-Length属性请求 412——一个或多个请求头字段在当前请求中错误 413——请求的资源大于服务器允许的大小 414——请求的资源URL长于服务器允许的长度 415——请求资源不支持请求项目格式 416——请求中包含Range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含If-Range请求头字段 417——服务器不满足请求Expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求 合起来 500——服务器产生内部错误 501——服务器不支持请求的函数 502——服务器暂时不可用,有时是为了防止发生系统过载 503——服务器过载或暂停维修 504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长 505——服务器不支持或拒绝支请求头中指定的HTTP版本
7.Ajax数据库动态通信 (1)用户请求页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <!DOCTYPE html > <html > <head > <meta charset ="utf-8" > <script > function showCustomer (str ) { var xmlhttp; if (str == "" ) { document .getElementById ("txtHint" ).innerHTML = "" ; return } if (window .XMLHttpRequest ) { xmlhttp = new XMLHttpRequest () } else { xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP" ) } xmlhttp.onreadystatechange = function ( ) { if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) { document .getElementById ("txtHint" ).innerHTML = xmlhttp.responseText } } xmlhttp.open ("GET" , "/try/ajax/getcustomer.php?q=" + str, true ); xmlhttp.send () } </script > </head > <body > <form action ="" > <select name ="customers" onchange ="showCustomer(this.value)" style ="font-family:Verdana, Arial, Helvetica, sans-serif;" > <option value ="APPLE" > Apple Computer, Inc.</option > <option value ="BAIDU " > BAIDU, Inc</option > <option value ="Canon" > Canon USA, Inc.</option > <option value ="Google" > Google, Inc.</option > <option value ="Nokia" > Nokia Corporation</option > <option value ="SONY" > Sony Corporation of America</option > </select > </form > <br > <div id ="txtHint" > 客户信息将显示在这...</div > </body > </html >
(2)Ajax服务器页面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <% response.expires=-1 sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID=" sql=sql & "'" & request.querystring ("q" ) & "'" set conn=Server.CreateObject ("ADODB.Connection" ) conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open (Server.Mappath ("/db/northwind.mdb" )) set rs=Server.CreateObject ("ADODB.recordset" ) rs.Open sql,conn response.write ("<table>" ) do until rs.EOF for each x in rs.Fields response.write ("<tr><td><b>" & x.name & "</b></td>" ) response.write ("<td>" & x.value & "</td></tr>" ) next rs.MoveNext loop response.write ("</table>" ) %>
8.使用XML示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 function loadXMLDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "cd_catalog.xml", true); xhttp.send(); } function myFunction(xml) { var i; var xmlDoc = xml.responseXML; var table="<tr > <th > Artist</th > <th > Title</th > </tr > "; var x = xmlDoc.getElementsByTagName("CD"); for (i = 0; i <x.length; i++) { table += "<tr > <td > " + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td > <td > " + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td > </tr > "; } document.getElementById("demo").innerHTML = table; }
9.Ajax请求Json示例 (1)请求页面文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <!DOCTYPE html > <html > <head > <meta charset ="utf-8" > <script > function loadXMLDoc ( ){ var xmlhttp; if (window .XMLHttpRequest ) { xmlhttp=new XMLHttpRequest (); } else { xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP" ); } xmlhttp.onreadystatechange =function ( ) { if (xmlhttp.readyState ==4 && xmlhttp.status ==200 ) { var myArr = JSON .parse (this .responseText ); myFunction (myArr) } } xmlhttp.open ("GET" ,"/try/ajax/json_ajax.json" ,true ); xmlhttp.setRequestHeader ("Content-Type" , "application/json;charset=UTF-8" ); xmlhttp.send (); } function myFunction (arr ) { var out = "" ; var i; for (i = 0 ; i < arr.length ; i++) { out += '<a href="' + arr[i].url + '">' + arr[i].title + '</a><br>' ; } document .getElementById ("myDiv" ).innerHTML =out; } </script > </head > <body > <h2 > AJAX JSON</h2 > <button type ="button" onclick ="loadXMLDoc()" > 请求 JSON 数据</button > <div id ="myDiv" > </div > </body > </html >
(2)Json文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [ { "title" : "JavaScript 教程" , "url" : "https://www.runoob.com/js/" } , { "title" : "HTML 教程" , "url" : "https://www.runoob.com/html/" } , { "title" : "CSS 教程" , "url" : "https://www.runoob.com/css/" } ]
(3)发送json数据 1 xmlhttp.send (JSON .stringify ({ "email" : "admin@runoob.com" , "response" : { "name" : "runoob" } }));
参考文献
Vue.js 菜鸟教程