1.http请求


定义:http计算机通过网络进行通信的规则
01.png
01.png

2.请求响应


  • open(method,url,asyn)
    asyn值默认为true
  • send()
  • onreadystatechange

3.一个完整的ajax的步骤


1.创建ajax核心对象

2.与服务器建立连接

3.发送请求 (url type:”get” dataType:”jsonp”)

4.响应

4.get和post的区别


1.从可见性 get方式传递的参数,是跟着url地址后面 post传递的参数是不可见
2.安全性
3.传递数据量大小 get有限制,post无限制
_

get请求

  1. var url = "https://www.easy-mock.com/mock/5bac6df10132334db7167178/testDemo/testDemo";
  2. var xhr = new XMLHttpRequest();
  3. xhr.open('get',url,true);
  4. xhr.send();
  5. xhr.onreadystatechange = function(){
  6. if(xhr.readyState == 4 && xhr.status == 200){
  7. var txt = JSON.parse(xhr.responseText);
  8. console.log(txt);
  9. }
  10. }

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

  • responseText:获取字符串形式的响应数据
  • status:以数字形式返回http的状态码
  • readystate值代表服务器响应的变化

01.png

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>