这里有一些 JavaScript:
$.ajax({
type: "POST",
url: "default.aspx/GetDate",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function(result) {
alert(result.d);
}
});
上面的方法按照我的预期工作,并警告从 [WebMethod] 返回的字符串,在 default.aspx 中调用 GetDate
但是当我使用时:
$.post(
"default.aspx/GetDate",
{},
function(result) {
alert(result.d);
},
"json"
);
此成功方法中的警报永远不会触发。
在 firebug 中,我可以看到 POST 基本上有效 - 它返回 200 OK
但本例中的响应是整个 default.aspx 页面的 HTML,而不是我使用 $.ajax() 方法时返回的 JSON。
编辑:
firebug 中显示的响应和请求 header 不相同。
使用 $.ajax()...
REQUEST:
Accept application/json, text/javascript, */*; q=0.01
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Accept-Encoding gzip, deflate
Accept-Language en-gb,en;q=0.5
Connection keep-alive
Content-Type application/json; charset=utf-8
Cookie (removed)
Host (removed)
Referer (removed)
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1
X-Requested-With XMLHttpRequest
RESPONSE:
Cache-Control private, max-age=0
Content-Length 27
Content-Type application/json; charset=utf-8
Date Wed, 11 Jan 2012 12:36:56 GMT
Server Microsoft-IIS/7.5
X-Powered-By ASP.NET
使用 $.post()...
REQUEST:
Accept application/json, text/javascript, */*; q=0.01
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Accept-Encoding gzip, deflate
Accept-Language en-gb,en;q=0.5
Connection keep-alive
Cookie (removed)
Host (removed)
Referer (removed)
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1
X-Requested-With XMLHttpRequest
RESPONSE:
Cache-Control private
Content-Length 13815
Content-Type text/html; charset=utf-8
Date Wed, 11 Jan 2012 12:36:53 GMT
Server Microsoft-IIS/7.5
X-AspNet-Version 2.0.50727
X-Powered-By ASP.NET
我可以使用 $.post() 方法来实现此目的,还是必须使用 $.ajax() 方法?
最佳答案
这很正常。当您使用 $.post
时,您无法像使用 $.ajax
那样设置 contentType: 'application/json'
。服务器需要这个 header 。因此基本上您不能使用 $.post
调用 ASP.NET 页面方法。
关于jquery - jquery的post()方法能够调用asp.net 3.5 webmethod吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8819973/