1. POST请求
POST请求主要用于向服务器发送应该被保存的数据,被发送的数据会在请求体中伴随请求发送到后台,该数据可以是任意大小,任意类型。
常见的POST请求应用场景就是注册、登录,以表单登录为例:
1.1 原生表单方式
<form action="http://bufantec.com/api/test/user/doLogin" method="POST">
<input type="text" name="username" class="uname">
<input type="password" name="password" class="pwd">
<button>登录</button>
</form>
上例展示了一个表单登录,当你输入用户名或密码后会提交到我们的后台地址,然后返回包含登录成功或者失败信息的JSON字符串。打开控制台,查看网络工作:
1.2 AJAX方式
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function (){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.response);
}
}
xhr.open("POST", "http://bufantec.com/api/test/user/doLogin");
// 多了一个请求头信息的设定, 我们需要根据后端程序员提供的接口文档, 设置相应的请求头信息
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
// 携带的参数信息放在send中
xhr.send("username=libai&password=123456");
content-type
:数据发送出去后,需要接收的服务端可以解析成功,一般服务端会根据此字段来获取参数是怎么编码的,然后对应去解码,一般认为content-type
有以下四种类型:+ `text/plain` AJAX请求的默认值 + `application/json` json格式, 目前支持率比较高的编码方式 + `application/x-www-form-urlencoded` form表单数据的提交编码设置 + `multipart/form-data` 二进制文件的编码方式 ( 常用来提交图片或者文件等 )
该字段的设定是跟后端程序员约定好的。发送请求时,需要将参数整理成约定的格式,发送出去。