AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

GET 还是 POST?

与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。

然而,在以下情况中,请使用 POST 请求:

  • 无法使用缓存文件(更新服务器上的文件或数据库)
  • 向服务器发送大量数据(POST 没有数据量限制)
  • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
  • More

 

封装ajax()函数,代码如下-----注意window.XMLHttpRequest中的window不能少,否则会出错。XMLHttpRequest相当于window的一个属性

 1 // JavaScript Document
 2 function ajax(url,fnSucc,fnFailed){
 3     //1.创建对象
 4     var oAjax=null;
 5     if(window.XMLHttpRequest){
 6         oAjax=new XMLHttpRequest();    
 7     }    
 8     else{
 9         oAjax=new ActiveXObject("Microsoft.XMLHTTP");    
10     }    
11     //alert(oAjax);
12     //2.连接服务器
13     //open(请求方式,url,是否异步)
14     oAjax.open('GET',url,true)
15     //3.发送请求
16     oAjax.send();
17     //4.返回数据
18     oAjax.onreadystatechange=function(){
19         if(oAjax.readyState==4){
20             if(oAjax.status==200){
21                 //alert("victory"+oAjax.responseText);
22                 fnSucc(oAjax.responseText);
23             }    
24             else{
25                 if(fnFailed){
26                     fnFailed();    
27                 }
28             }
29         }    
30     }
31 };

ajax()函数测试版

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>无标题文档</title>
 6 <script>
 7     //用未定义的变量会出错------用未定义的属性undefined
 8     //alert(a);
 9     //alert(window.a);
10     window.onload=function(){
11         var oBtn=document.getElementById('btn');
12         oBtn.onclick=function(){
13             //1.创建对象
14             var oAjax=null;
15             if(window.XMLHttpRequest){
16                 oAjax=new XMLHttpRequest();    
17             }    
18             else{
19                 oAjax=new ActiveXObject("Microsoft.XMLHTTP");    
20             }    
21             //alert(oAjax);
22             //2.连接服务器
23             //open(请求方式,url,是否异步)
24             oAjax.open('GET','abc.txt',true)
25             //3.发送请求
26             oAjax.send();
27             //4.返回数据
28             oAjax.onreadystatechange=function(){
29                 if(oAjax.readyState==4){
30                     if(oAjax.status==200){
31                         alert("victory"+oAjax.responseText);
32                     }    
33                     else{
34                         alert("defeat!");    
35                     }
36                 }    
37             }
38         };
39     }
40     
41 </script>
42 </head>
43 
44 <body>
45 <input type="button" id="btn" value="create">
46 </body>
47 </html>
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-04-19
  • 2021-05-26
  • 2021-08-28
  • 2022-02-16
  • 2021-11-16
猜你喜欢
  • 2022-12-23
  • 2022-01-16
  • 2021-12-19
  • 2021-12-06
  • 2022-01-16
  • 2021-12-05
  • 2022-12-23
相关资源
相似解决方案