一、http请求

  1. ![](https://cdn.nlark.com/yuque/0/2019/png/402672/1567162734850-7caf8cd6-f8fd-4e3b-9518-36f105f2cd9d.png#align=left&display=inline&height=403&originHeight=403&originWidth=633&size=0&status=done&style=none&width=633)<br />![](https://cdn.nlark.com/yuque/0/2019/png/402672/1567162744275-ef3d2be2-19e0-41d7-9148-041e2cf2b430.png#align=left&display=inline&height=299&originHeight=299&originWidth=753&size=0&status=done&style=none&width=753)<br />![](https://cdn.nlark.com/yuque/0/2019/png/402672/1567162718923-b14fb649-4615-4910-b846-b7cee506449f.png#align=left&display=inline&height=258&originHeight=258&originWidth=762&size=0&status=done&style=none&width=762)<br />![](https://cdn.nlark.com/yuque/0/2019/png/402672/1567162763492-695003ec-51df-43bf-97fc-54a56b3dbb26.png#align=left&display=inline&height=242&originHeight=242&originWidth=741&size=0&status=done&style=none&width=741)<br />![](https://cdn.nlark.com/yuque/0/2019/png/402672/1567162772768-ea771337-0fde-4bbb-95c3-cecd18aa074e.png#align=left&display=inline&height=297&originHeight=297&originWidth=703&size=0&status=done&style=none&width=703)

二、get方法

JSON.parse()方法将json对象解析为JavaScript对象。
JSON.stringify()将javascript的值,转换为JSON字符串。

  1. <p id="name"></p>
  2. <p id="age"></p>
  3. <script>
  4. var url="https://www.easy-mock.com/mock/5d67436224fd60626abfe906/ajax/base";
  5. var xhr=new XMLHttpRequest();
  6. xhr.open('get',url,true) //true 异步
  7. xhr.send()
  8. xhr.onreadystatechange=function(){
  9. /* console.log(xhr.readyState)
  10. console.log(xhr.status) */
  11. if(xhr.readyState==4 && xhr.status==200){ //请求已完成 200:请求成功
  12. var res=JSON.parse(xhr.responseText);
  13. console.log(res.data.name)
  14. var name=document.getElementById("name")
  15. name.innerHTML=res.data.name;
  16. }
  17. }
  18. </script>

2-1 responseText:获取字符串形式的响应数据

2-2 status:以数字形式返回http的状态码

二、http,get,post - 图2

2-3readystate值代表服务器响应的变化

二、http,get,post - 图3

三、post方法

post方式要设置一个请求头

  1. <div id="test"></div>
  2. <script>
  3. var test = document.getElementById("test");
  4. var xhr = new XMLHttpRequest();
  5. xhr.open("post","https://www.easy-mock.com/mock/5b230e1e6bed703a9b488c69/www.getTest.com/push",true);
  6. xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  7. xhr.send(null);
  8. xhr.onreadystatechange = function(){
  9. if(xhr.readyState == 4 && xhr.status == 200){
  10. var data = JSON.parse(xhr.responseText);
  11. test.innerHTML = data.data.content
  12. }
  13. }
  14. </script>

四、get和post的区别

  1. 1.可见性 get方式传递的参数是跟着url地址后面的;post传递的参数是不可见的<br /> 2.安全性 post更安全<br /> 3.传递数据量大小 get有限制,一般在2000字符左右;post无限制