ajax实现数据提取

 1 function ajax(options){
 2     return new Promise(function(resolve,reject){
 3         var xhr = new XMLHttpRequest() || ActiveXObject("Microsoft,XMLHTTP");
 4         //拼接参数
 5         var str = "";
 6         if(options.data){
 7              for(key in options.data){
 8                 str += '&' + key + "=" + options.data[key];
 9             }
10         };
11         //判断提交方式
12         if(options.method == 'get'){
13             xhr.open("get",options.url + "?" + str.slice(1));
14             xhr.send();
15         }else{
16             xhr.open("post",options.url);
17             xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
18             xhr.send(str.slice(1));
19         };
20         xhr.onreadystatechange = function(){
21             //如果请求成功的情况下 数据直接交给 resolve(data);
22             if(xhr.readyState == 4 && xhr.status == 200){
23                 resolve(JSON.parse(xhr.responseText));
24             }
25 
26             //如果数据请求失败  
27             setTimeout(function(){
28                 if(xhr.readyState != 4 || xhr.status != 200){
29                     var objState = {
30                         state : xhr.readyState,
31                         status :  xhr.status
32                     };
33                     reject(objState)  //reject只能返回一个结果
34                 }
35             },3000)    //异步指向需要等待
36         } 
37     })
38 }
39 //调用该方法示例
40 /*
41     document.onclick = function(){
42         ajax({
43         'method' : 'get',
44         'url' : 'http://localhost/data.php',
45         'data': {
46             'id' : 'VIP'
47         }
48     }).then(function(data){
49         console.log(data);
50     }).catch(function(data){
51         console.log(data)
52     })
53     }
54 */

下面是被提取的一个php文件示例
 1 <?php
 2     header("content-type:text/html;charset:utf8");
 3     $vip = $_REQUEST["id"];
 4     $arr = Array(
 5         Array(
 6             "id" => "1",
 7             "name" => "小红"
 8         ),
 9         Array(
10             "id" => "2",
11             "name" => "小亮"
12         ),
13         Array(
14             "id" => "3",
15             "name" => "小明"
16         ),
17         Array(
18             "id" => $vip,
19             "name" => "小瑶"
20         ),
21         Array(
22             "id" => "5",
23             "name" => "小飞"
24         )
25     );
26     echo json_encode($arr);
27 ?>


 
知识在于点滴积累
原文地址:https://www.cnblogs.com/XieYFwin/p/10849748.html