AJAX请求和普通HTTP请求区别(postman分析)

版权声明:分享才能获得最大的价值 https://blog.csdn.net/qq_32252957/article/details/84348155

两者本质区别:
AJAX通XMLHttpRequest对象请求服务器服务器接受请求返数据实现刷新交互
普通http请求通httpRequest象请求服务器接受请求返数据需要页面刷新

AJAX请求头会多一个x-requested-with参数,值为XMLHttpRequest

下面我用postman模拟Ajax请求我本地服务器上的sales.json数据

我们用Post方法,模拟表单输入,头部加入了两个键值对信息,Body请求体加入了两个键值对,分别是username和password

postman生成的代码是:

其中之一是javascript实现的

var data = new FormData();
data.append("username", "clarence");
data.append("password", "123456");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost/sales.json");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "dc9c60bb-f440-4caa-850b-60941140ae7f");

xhr.send(data);

下面是请求报文的构成: 

可以看到请求头部(请求方法, URL, 协议/版本)、请求行、请求body

Content-disposition是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件.

扫描二维码关注公众号,回复: 4529622 查看本文章

可以看到是表单数据,分别说用户名和密码

POST /sales.json HTTP/1.1
Host: localhost
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
X-Requested-With: XMLHttpRequest
Cache-Control: no-cache
Postman-Token: 73219f21-8a1d-4c61-825a-5ffab5cc774f

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="username"

clarence
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="password"

123456
------WebKitFormBoundary7MA4YWxkTrZu0gW--

猜你喜欢

转载自blog.csdn.net/qq_32252957/article/details/84348155