經過嘗試,只需要在$.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");
$.getJSON代碼
代碼如下:
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");
});
$.post代碼
代碼如下:
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');
用HttpWatch查看請求返回的數據如下:
代碼如下:
<?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.