jquery的post()方法是否能够调用asp.net 3.5 webmethod?

时间:2012-01-11 13:20:36

标签: jquery asp.net ajax webmethod

这是一些javascript:

$.ajax({
        type: "POST",
        url: "default.aspx/GetDate",
        contentType: "application/json; charset=utf-8",
        data: {},
        dataType: "json",
        success: function(result) {
            alert(result.d);
        }
     });

上述方法可以正常工作,并在default.aspx

中提醒[WebMethod]返回的名为GetDate的字符串。

但是当我使用时:

$.post(
        "default.aspx/GetDate",
        {},
        function(result) {
            alert(result.d);
        },
        "json"
     );

此成功方法中的警报永远不会触发。

在萤火虫中我可以看到POST基本上有效 - 它返回200 OK
但是在这种情况下的响应是整个default.aspx页面的HTML,而不是我使用$ .ajax()方法时返回的JSON。

编辑:
firebug中显示的响应和请求标头不相同。

使用$ .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()方法?

2 个答案:

答案 0 :(得分:3)

这是正常的。当您使用$.post时,无法像contentType: 'application/json'那样设置$.ajax。并且服务器期望此标头。所以基本上你不能用$.post调用ASP.NET页面方法。

答案 1 :(得分:3)

我认为这是因为您的服务器端代码要求设置Content-Type标头。 $.post的默认实现不允许这样做。

但是,如果您在应用程序中每次使用AJAX都需要此标题,则可以修改$.post

$.post = function (url, data, callback, type) {
    if (jQuery.isFunction(data)) {
        type = type || callback;
        callback = data;
        data = undefined;
    }

    return jQuery.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: callback,
        dataType: type
        contentType: "application/json; charset=utf-8"
    });
};

有了这个,所有 $.post次来电都会设置contentType。这可能是一个好主意;它可能不会......