ajax 小案例

ajax 异步提交数据,实现无刷新提交表单

ajax.html

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <span>    用户名:<input type="text" name="name" />&nbsp;&nbsp;<span id="span"></span></span><br />
 9         <div id="div">
10             <input type="button" value="点击" onclick="ajax()" />     
11         </div>
12         <span>    用户名:<input type="text" name="name" />&nbsp;&nbsp;<span id="span2"></span></span><br />
13         <div id="div2">
14             <input type="button" value="点击" onclick="ajax2()" />     
15         </div>
16         
17         <script>
18             
19             function ajax(){
20                 var xmlHttp;
21                 if(window.XMLHttpRequest){
22                     xmlHttp = new XMLHttpRequest();
23                 }else 
24                     xmlHttp = ActiveXObject("Microsoft.XMLHTTP");
25                     
26                 xmlHttp.onreadystatechange = function(){
27                     if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
28                         var inner =xmlHttp.responseText;
29                         var obj = eval(inner);
30                 //        alert(obj);
31                         document.getElementById("span").innerHTML = obj[0].first;
32                     }
33                 }
34                 
35                 xmlHttp.open("GET","ch.json",true);
36                 xmlHttp.send();
37             }
38             
39             function ajax2(){
40                 var xmlHttp;
41                 if(window.XMLHttpRequest){
42                     xmlHttp = new XMLHttpRequest();
43                 }else 
44                     xmlHttp = ActiveXObject("Microsoft.XMLHTTP");
45                     
46                 xmlHttp.onreadystatechange = function(){
47                     if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
48                         var inner =xmlHttp.responseText;
49                         var obj = eval(inner);
50                         document.getElementById("span2").innerHTML = obj[0].second;
51                     }
52                 }
53                 
54                 xmlHttp.open("GET","ch.json",true);
55                 xmlHttp.send();
56             }
57         </script>
58     </body>
59 </html>

ch.json

 

1 {
2     [
3         {"first":"用户名可以用","second":"用户名不可以用"}
4     ]
5 }

 结果图:

ajax 小案例_第1张图片

 ajax 小案例_第2张图片

 

你可能感兴趣的:(ajax 小案例)