Posted in Javascript onJuly 28, 2011
经过尝试,只需要在$.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.
jQuery.get、jQuery.getJSON、jQuery.post无法返回JSON问题的解决方法
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@