原生JS写Ajax的请求函数

 已上传至githubhttps://github.com/hajnalmin/ajaxJS.git  

  如果对你有帮助的话,就去给个星吧~么么哒~笔芯

ajax:一种请求数据的方式,不需要刷新整个页面;
ajax的技术核心是 XMLHttpRequest 对象;
ajax 请求过程:创建 XMLHttpRequest 对象、连接服务器、发送请求、接收响应数据;

调试过程中需要搭建apache服务

HTML文件如下:(有详细的注释)

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>原生js的ajax</title>
 6 </head>
 7 <body>
 8 <!--
 9     原生js封装ajax方法
10 
11 -->
12 
13 <script>
14     //1.处理get请求
15     function ajax(option){
16         //1.实例化ajax
17 
18         var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("microsoft.xmlhttp");
19 
20         //2.判断请求方式是否为get
21         var isGET = /get/i.test(option.method);
22 
23 
24         //3. 将json数据转换为字符串格式  属性名=值&。。。
25         var data = "";
26         for(var i in option.data){
27             //4.将数据拼成字符串
28             data +=i+"="+ option.data[i]+"&";
29         }
30 
31         //5.将处理好的数据字符串替换原有的数据
32         option.data = data;
33 
34         //判断是否是get方法,如果是检查url中有没有?然后再把data数据加到?后
35         if(isGET){
36             if(option.url.indexOf("?")<0){
37                 option.url+='?';
38             }
39             option.url+=+"&"+option.data;
40         }
41 
42         //6 判断是否启用缓存,如果不启用缓存 添加时间
43         if(!option.cache){
44             //7向URL上补充时间
45             option.url+="&___="+new Date().getTime();
46         }
47         //打开连接
48         xhr.open(option.method,option.url,option.async);
49         //7.如果是post请求则设置请求头
50         if(!isGET){
51             xhr.setRequestHeader('content-type','application/xml-form-urlencoded');
52         }
53 
54         //8.发送请求
55         xhr.send(option.data);
56         //9.ajax状态改变时触发函数
57         xhr.onreadystatechange = function(){
58             //判断ajax是否加载完成
59             if(xhr.readyState == 4){
60                 //判断页面是否请求成功
61                 if(xhr.status == 200){
62                     option.success(xhr.responseText);
63                 }else{
64                     option.error(xhr.status)
65                 }
66             }
67 
68         }
69 
70     }
71 
72     ajax({
73         method:'get',
74         url:"01.php?name=Kitty",
75         async:true,
76         data:{age:12,sex:"girl"},
77         cache:true,
78         sendBefore:function(xhr){
79             console.log("loading···");
80         },
81         sendComplete:function(xhr){
82             console.log("loading完成");
83         },
84         success:function(txt){
85             console.log("请求成功,服务器返回数据为:"+txt);
86         },
87         error:function(status){
88             console.log("请求失败状态码为:"+status);
89         }
90     });
91 
92 </script>
93 </body>
94 </html>

PHP文件如下:(仅做测试用

<?php
    
    echo 'get<pre>';
    print_r($_GET);
    
    echo 'post<pre>';
    print_r($_POST);
    

运行成功后的显示:

注意:如果不是在Apache服务器下,会显示以下信息

有什么问题欢迎交流沟通~大家一起学习~

原文地址:https://www.cnblogs.com/Hmin2199/p/6431507.html