1.http请求

  1. ![](https://cdn.nlark.com/yuque/0/2019/png/402672/1567162734850-7caf8cd6-f8fd-4e3b-9518-36f105f2cd9d.png#align=left&display=inline&height=403&margin=%5Bobject%20Object%5D&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&margin=%5Bobject%20Object%5D&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&margin=%5Bobject%20Object%5D&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&margin=%5Bobject%20Object%5D&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&margin=%5Bobject%20Object%5D&originHeight=297&originWidth=703&size=0&status=done&style=none&width=703)

2.get请求

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

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

2.1responseText:获取字符串形式的响应数据

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

第二节 http,post,get - 图2

2.3readystate值代表服务器响应的变化

第二节 http,post,get - 图3

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>

4.get和post的区别

1.可见性 get方式传递的参数是跟着url地址后面的;post传递的参数是不可见的

2.安全性 post更安全

3.传递数据量大小 get有限制,一般在2000字符左右;post无限制

git和post区别

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