jQuery.get、jQuery.getJSON、jQuery.post无法返回JSON问题的解决方法
经过尝试,只需要在$.ajax中加入 contentType: "application/json; charset=utf-8"选项就可以了,这是因为在.net 3.5以后要对contentType进行检查,所以仅仅指定dataType的话.net就不会返回JSON了,那么我们的请求自然也就无法请求到JSON数据了。正确写法就是这样了:
代码如下:
var url = "/Services/AccountService.asmx/UserExists";
var userName = $("#txtUserName").val();
$.ajax({
type: "POST",
url: url,
data: '{userName:"'+userName+'"}',
dataType: "json",
success: function (json) {
if (json.d == true) {
$("#submit").removeAttr("disabled");
return;
}
$("#submit").attr("disabled", "disabled");
}
});
var url = "/Services/AccountService.asmx/UserExists";
var userName = $("#txtUserName").val();
$.ajax({
type: "POST",
url: url,
data: '{userName:"'+userName+'"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
if (json.d == true) {
$("#submit").removeAttr("disabled");
return;
}
$("#submit").attr("disabled", "disabled");
}
});
但是在使用$.get、$.getJSON、$.post时确怎么也得不到JSON数据了,写法如下:
$.get代码
代码如下:
var url = "/Services/AccountService.asmx/UserExists";
var userName = $("#txtUserName").val();
$.get(
url
, { userName: userName }
, function (json) {
if (json.d == true) {
$("#submit").removeAttr("disabled");
return;
}
$("#submit").attr("disabled", "disabled");
},"json");
var url = "/Services/AccountService.asmx/UserExists";
var userName = $("#txtUserName").val();
$.getJSON(
url
, { userName: userName }
, function (json) {
if (json.d == true) {
$("#submit").removeAttr("disabled");
return;
}
$("#submit").attr("disabled", "disabled");
});
var url = "/Services/AccountService.asmx/UserExists";
var userName = $("#txtUserName").val();
$.post(
url
, { userName: userName }
, function (json) {
if (json.d == true) {
$("#submit").removeAttr("disabled");
return;
}
$("#submit").attr("disabled", "disabled");
},'json');
<?xml version="1.0" encoding="utf-8"?>
<boolean xmlns="http://tempuri.org/">false</boolean>
看一下jQuery.extend中有关代码:
jQuery.extend
代码如下:
jQuery.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
});
原因就是.net 3.5以后要对contentType进行检查,如果不为json的话,就不会返回json,而get、getJSON、post扩展都再次调用了ajax,但是只传了dataType参数,.net 3.5在检查contentType时发现其不是json,便返回了xml.