项目场景:
前后端做数据交换时,使用XMLHttpRequest类做网络连接。该类有open(),send()函数,其中open()需要传递请求方式(POST,GET…),uri等,send()函数可以传递请求参数。
问题描述
在使用open()函数传递GET请求参数时,在后端获取不到传递过来的参数,显示参数为null,而直接把参数拼接在uri上时,后端确实可以收到参数数据。
原因分析:
1.open()函数不支持GET请求的参数传递。
2.POST请求时,open()函数接受的参数不包括序列化后的 JSON 字符串,由于post请求的默认content-type 是application/json,也就是接收序列化后的 JSON 字符串,所以导致参数依然不能传输。
解决方案:
所以POST请求需要修改content-type为 application/x-www-form-urlencoded,content-type的application/x-www-form-urlencoded会将参数编码成键值对。而GET请求则把参数拼接在uri上传递。 示例代码如下:
post请求:
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {};
xhr.open("POST", "http://localhost:8081/CollectStar/PaiHangBang/", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-formurlencoded');
xhr.send("test=123");
get请求:
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {};
xhr.open("GET", "http://localhost:8081/CollectStar/PaiHangBang?test=123", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-formurlencoded');
xhr.send();