使用AJAX调用服务器端方法

Calling server side method using AJAX

本文关键字:方法 服务器端 调用 AJAX 使用      更新时间:2023-09-26

我试图通过使用AJAX从客户端调用服务器端的函数来测试它。

每次调用AJAX方法时都会出现以下错误:

http://localhost:5958/myaccount/notifications/myaccount/notifications/Default.aspx/method加载资源失败:服务器响应状态为404(未找到)

这是我的AJAX函数:

    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "myaccount/notifications/Default.aspx/method",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }

HTML控件:

<input id="btnGetTime" type="button" value="Show Current Time"
    onclick="ShowCurrentTime()" />

我试图在服务器端调用的函数:

        [WebMethod]
    protected bool method()
    {
        return true;
    }

正确的做法是什么?

更新

将url更改为:'<%= ResolveUrl("~/default.aspx/method") %>',现在我收到500内部服务器错误。

更新2

内部错误是由[HttpPost]属性引起的,我将其更改为[WebMethod],它可以工作。

我认为问题出在您的url中。

使用类似于下面的前导斜杠(/)。

url:"/myaccount/notifications/Default.aspx/method"

您的服务器端调用必须是静态公共调用。https://msdn.microsoft.com/en-us/library/bb398998(v=vs.90).aspx

[WebMethod]
public static bool method()
{
    return true;
}

我假设您没有传递任何参数。因此,您可以尝试Data:{}而不是Data:"{}"吗。

相关文章: