【问题标题】:Using jQuery to directly call ASP.NET AJAX page methods -- 500 (Internal Server Error)使用jQuery直接调用ASP.NET AJAX页面方法——500(Internal Server Error)
【发布时间】:2014-02-07 13:44:20
【问题描述】:

我正在通过 ajax 学习 asp 方法和...

所以我试着做ff。来自本站:http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

在JS文件中:

 $(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
    $.ajax({
        type: "POST",
        url: "WebForm1.aspx/GetDate",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Replace the div's content with the page method's return.
            $("#Result").text(msg.d);
        }
    });
});

});

在 aspx 中:

 <html>
<head>
<title>Calling a page method with jQuery</title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="Scripts/JScript1.js"></script>
 </head>
  <body>
<div id="Result">Click here for the time.</div>
 </body>
 </html>

在代码隐藏中:

namespace WebApplication1
 {
   public partial class WebForm1 : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }

}

}

当我在本地 PC 上的 VS studio 上运行它时,它工作得很好;但是,一旦文件部署在 IIS 服务器中,当我单击容器时会出现此错误:

POST http:///WebForm1.aspx/GetDate 500(内部服务器错误)

在 IIS 中有什么需要配置的吗?还是与代码相关的错误?

【问题讨论】:

    标签: jquery asp.net ajax iis webmethod


    【解决方案1】:

    尝试删除此行 [ScriptMethod(UseHttpGet = true)] 因为此行用于当您尝试获取请求时,当您看到示例时,他们正在尝试执行 POST 请求并且不需要此行。

    [WebMethod]
        public static string GetDate()
        {
            return DateTime.Now.ToString();
        }
    

    【讨论】:

    • 好点,但正如 Bart 所建议的那样,最好将 AJAX 调用改为 get,因为它确实是从服务器获取一些东西,而不是发布一些东西。
    • @Bartdude 是的,我认为我解释得不好,但是如果您看到 OP 发布的示例,您会看到他正在尝试进行 Post 请愿。
    • 好吧,我看到他正在尝试调用Getdate() 方法。无论如何,您的答案是正确的,并且会解决 Op 的问题,但最好使用正确的 HTTP 方法,尤其是当您谈论 get 和 post 时。
    • 太酷了!它起作用了~我想我没有注意到“GET”部分,我正在尝试做 POST。但是也感谢@Bartdude的提醒,谢谢大家~ :)
    【解决方案2】:

    您正在向 GET 方法发出 POST 请求,请尝试将您的 javascript 更改为:

    $("#Result").click(function () {
        $.get("WebForm1.aspx/GetDate", function (msg) {
            // Replace the div's content with the page method's return.
            $("#Result").text(msg.d);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2015-09-15
      • 2020-02-01
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多