使用 jQuery 调用 ASP.NET PageMethod/WebMethod - 返回整个页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/583116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:23:33  来源:igfitidea点击:

Call ASP.NET PageMethod/WebMethod with jQuery - returns whole page

asp.netjqueryweb-servicesasmxpagemethods

提问by Matt

jQuery 1.3.2, ASP.NET 2.0. Making an AJAX call to a PageMethod (WebMethod) returns the full/whole page instead of just the response. A breakpoint on the page method shows it's never getting hit. I have the [WebMethod] attribute on my method, and it ispublic static, returns string and accepts no params. I even tried adding [ScriptService] at the top of my class to see if it helped, but it did not.

jQuery 1.3.2,ASP.NET 2.0。对 PageMethod (WebMethod) 进行 AJAX 调用将返回完整/整个页面,而不仅仅是响应。页面方法上的断点显示它永远不会被击中。我的方法有 [WebMethod] 属性,它公共静态的,返回字符串并且不接受任何参数。我什至尝试在班级顶部添加 [ScriptService] 以查看是否有帮助,但没有。

I have seen this post Jquery AJAX with ASP.NET WebMethod Returning Entire Pagewhich had my same symptoms, but I am still having a problem. I read http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/and I feel like I'm following this to the T, but still no luck.

我看过这篇文章Jquery AJAX with ASP.NET WebMethod Returning Entire Page,它有我相同的症状,但我仍然有问题。我读了http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/我觉得我正在关注这个 T,但仍然没有运气。

The jQuery call I'm making is:

我正在调用的 jQuery 是:

jQuery.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: '{}',
    dataType: 'json',
    url: 'MyPage.aspx/SomePageMethod',
    success: function(result){
        alert(result);
    }
});

The request/response headers, as per Firebug in FF3, are as follows

根据 FF3 中的 Firebug,请求/响应标头如下

Response Headers
Server  ASP.NET Development Server/8.0.0.0
Date    Tue, 24 Feb 2009 18:58:27 GMT
X-AspNet-Version    2.0.50727
Cache-Control   private
Content-Type    text/html; charset=utf-8
Content-Length  108558
Connection  Close

Request Headers 
Host    localhost:2624
User-Agent  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6
Accept  application/json, text/javascript, */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  300
Connection  keep-alive
Content-Type    application/json; charset=utf-8
X-Requested-With XMLHttpRequest
Referer http://localhost:2624/MyApp/MyPage.aspx
Content-Length  2
Cookie  ASP.NET_SessionId=g1idhx55b5awyi55fvorj055; 

I've added a ScriptManager to my page just for kicks to see if it helped, but no luck there.

我在我的页面中添加了一个 ScriptManager 只是为了看看它是否有帮助,但没有运气。

Any suggestions?

有什么建议?

采纳答案by Dave Ward

Do you know that Page Methods are working properly? If you use the the ScriptManager do they work?

您知道 Page Methods 工作正常吗?如果您使用 ScriptManager,它们会起作用吗?

It sounds like you might be missing a web.config entry. Specifically the HttpModules section.

听起来您可能缺少web.config 条目。特别是 HttpModules 部分。

回答by Dave Ward

I was missing one line from my web.config:

我在 web.config 中遗漏了一行:

<system.web>
  <httpModules>
    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </httpModules>
</system.web>

回答by Matt

I encountered this problem again today for a different reason: I had misspelled "application" in

由于不同的原因,我今天再次遇到这个问题:我在

contentType: 'application/json'

And was getting a full-page response instead of a call to the WebMethod.

并且正在获得整页响应,而不是对 WebMethod 的调用。

回答by Marvin Zumbado

If you have tried all that and still get the whole page returned from your pagemethod, you may want to make sure you are not using friendly urls. If you are using them, this trick may help you

如果您已经尝试了所有这些并且仍然从您的 pagemethod 返回整个页面,您可能需要确保您没有使用友好的 url。如果您正在使用它们,这个技巧可能会对您有所帮助

Add this line on your js script before you make the call:

在调用之前在 js 脚本中添加以下行:

PageMethods.set_path(PageMethods.get_path() + '.aspx');

回答by Dan Simon

Throwing this out here as a side note. I was getting that error due to the length of my string variables in my HTML string and the website I used to get my ajax called looked like this.

把它扔在这里作为旁注。由于我的 HTML 字符串中的字符串变量的长度和我用来调用 ajax 的网站看起来像这样,我收到了该错误。

loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "Default.aspx" : loc;
        $.ajax({
            type: "POST",
            url: loc + "/" + methodName,
            data: "{" + args + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: onSuccess,
            error: onFail
        });

It wasn't capable of extracting the .aspx link correctly, so I just hardcoded my webpage instead of using the loc var.

它无法正确提取 .aspx 链接,所以我只是硬编码了我的网页,而不是使用 loc var。

回答by Dan Simon

Most ajax scenarios I've seen really should call a web service or separate script handler, not a page. That is extremely easy to do in .net 3-5, not so easy in 2-0. Even after you figure out (if) how not to load the whole page, here are reasons not to call a page method:

我见过的大多数 ajax 场景确实应该调用 Web 服务或单独的脚本处理程序,而不是页面。这在 .net 3-5 中非常容易做到,而在 2-0 中就不那么容易了。即使在您弄清楚(如果)如何不加载整个页面之后,以下是不调用页面方法的原因:

1) The page method might load less stuff than a full page load, but still far more than you need for a simple ajax call. 2) Lousy separation of responsibilities. The page is probably responsible for nicely laying stuff out, not the logic you are using in the ajax method.
3) Maybe you need some session state, but that should still be available.

1) page 方法加载的内容可能比完整页面加载少,但仍远超简单 ajax 调用所需的内容。2) 职责分工很糟糕。该页面可能负责很好地布置内容,而不是您在 ajax 方法中使用的逻辑。
3) 也许你需要一些会话状态,但它应该仍然可用。

I'm currently updating my knowledge on this subject ... I'll look for a good answer to this question in this thread, or I'll post one next week. Here is the direction I am headed

我目前正在更新我对这个主题的知识......我会在这个线程中寻找这个问题的一个很好的答案,或者我会在下周发布一个。这是我前进的方向

1) Send JSON from server to client, and use javascript to update your page. - a variety of frameworks make it easy to produce JSON from the web server.
2) JQuery makes ajax calls, json handling, and client formatting fun, instead of painful.

1) 从服务器向客户端发送 JSON,并使用 javascript 更新您的页面。- 各种框架使从 Web 服务器生成 JSON 变得容易。
2) JQuery 使 ajax 调用、json 处理和客户端格式化变得有趣,而不是痛苦。

回答by Sotiris Zegiannis

After almost two hours and after had tried everything i finally solved it.@Marvin Zumbado's comment helped me.I was missing the .aspx from my url.I know this is not my best moment as a programmer!

将近两个小时后,在尝试了所有方法之后,我终于解决了。@Marvin Zumbado 的评论对我有帮助。我的 url 中缺少 .aspx。我知道这不是我作为程序员的最佳时刻!

回答by Hassan Nazeer

Commenting the following line in RouteConfig.cs works for me

在 RouteConfig.cs 中评论以下行对我有用

 settings.AutoRedirectMode = RedirectMode.Permanent;