记一次JS post开发遇到的坑

今天在写登陆注册页面的时候遇到个小问题

我使用xhr进行POST 下面是我代码

$("#id20").click(function(){

var account=$("#id16").text()

var pass=$("#id18").text()

var time=new Date().getTime()

if (window.XMLHttpRequest) {

//IE7+,及主流浏览器

var xhr = new XMLHttpRequest();

} else{

//IE 5, 6

var xhr = ActiveXObject("Microsoft.XMLHTTP");

}

xhr.open("POST","url");

xhr.send("account="+account+"&password="+pass+"&t="+time)

xhr.onreadystatechange = function(){

console.log(xhr.readyState);

if(xhr.readyState == 4){

//判断请求是否成功

if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {

//请求成功

console.log("请求成功")

var reslut=xhr.responseText

var jup=JSON.parse(xhr.responseText);

console.log(reslut)

if(jup.code==200){

console.log("登陆成功")

self.location="index.html"

}

} else{

//请求失败

console.log("请求失败")

}

}

}

})

但是返回值中缺说我缺少时间变量

通过抓包分析发现协议头中

Content-Type: text/plain;charset=UTF-8这个协议头会让后端读取不到post数据

在前端代码中加入协议头:Content-Type: application/x-www-form-urlencoded即可

如果提交的是json格式数据则修改为

Content-type: application/json

小知识

在http协议中content-type这个协议头代表的就是参数格式

希望对于大家有所帮助!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容