XHR对象的get请求

昨天美图面试有一题是写出XHR是什么以及写出其get请求的代码。
其实我前几天才写过,不过之后又写了angular.js的$http的get请求,原生的一时间想不起来,就用angular.js写了。
其实原生的也不复杂
先给出代码:
//JS
var xhr=new XMLHttpRequest();
   xhr.onreadystatechange=function () {
       if(xhr.readyState==4){
                if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
               var res=JSON.parse(xhr.responseText);
               alert(res["name1"]);
               alert(res['name2']);
           }else{
               alert("Unsuccessful:"+xhr.status);
           }
       }
   };
   xhr.open("get","test.php?name1=value1&name2=value2",true);
   xhr.send(null);  
//PHP:
$arr['name1']= $_GET["name1"];
$arr["name2"]=$_GET["name2"];
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
  • open函数的第三个参数表示请求是否是异步的
 xhr.open("get","test.php?name1=value1&name2=value2",true);
  • 返回的JSON数据不要忘记解析为JS对象
var res=JSON.parse(xhr.responseText);

版权声明:本文为huangpin815原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。