ajax實現數據提取
阿新 • • 發佈:2019-05-11
out || active cat mis utf change sta onclick
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 ?>
ajax實現數據提取