您的位置:首页 > Web前端 > JQuery

jquery 的ajax请求 之都是 dataType 缺失惹的祸

2016-03-31 00:00 549 查看
摘要: 好久没写前台了,今天练练手 ,却被一个问题卡主了好久,特此记下来

事情的起因:做一个简单的权限登录界面,涉及到通过页面发送异步1请求来校验验证码的功能:

$.ajax({
type : "post",
url : "./login.do",
data : {

account : account,
passWord : passWord,
code : code
},
//请求成功后的回调函数有两个参数
success : function(data, textStatus) {
if (data.status != 0) {
$("#message").text(data.msg);
} else {
window.location = "./index";
}
},
error : function(data, textStatus) {
$("#message").text(data.msg);
}
});

故意输入错误的验证码,得到服务器返回的json数据,页面上本该出现错误提示信息,然而一直没有出现,然后用页面debug,发现页面接收到了服务器端返回的json数据

{"status":1,"msg":"验证码输入错误","data":null}

,很奇怪没错啊,继续用debug,发现data.msg 为undefined,纳闷了,搞了很久,最后发现返回的数据类型是text/plain,原来是自己少写了一个希望服务器返回的数据类型dataType: "json", 默认接收类型为字符串。

改正后的代码:

$.ajax({
type : "post",//请求方式
url : "./login.do",//发送请求地址
dataType: "json",
contentType: "application/json; charset=utf-8",
data : {
account : account,
passWord : passWord,
code : code
},
//请求成功后的回调函数有两个参数
success : function(data, textStatus) {
if (data.status != 0) {
$("#message").text(data.msg);
} else {
window.location = "./index";
}
},
error : function(data, textStatus) {
$("#message").text(data.msg);
}
});


其中几个参数的含义在巩固一下

  type:请求方式,又称Method
  dataType:预期返回类型(The type of data that you're expecting back from the server)
  contentType:发送到服务器的数据的编码类型(When sending data to the server, use this content type)
  data:发送到服务器的数据
总结:温故而知新,知识需要不断的重复,遇到问题认真分析原因~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jQuery ajax