简体   繁体   中英

Calling server side method using AJAX

I'm trying to test a function that is on the server side by calling it from the client side using AJAX.

I get this error every time I invoke the AJAX method:

http://localhost:5958/myaccount/notifications/myaccount/notifications/Default.aspx/method Failed to load resource: the server responded with a status of 404 (Not Found)

Here's my AJAX function:

    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 control :

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

Function I'm trying to call on the server side:

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

What's the correct way of doing this?

Update

Changed the url to : '<%= ResolveUrl("~/default.aspx/method") %>' and now I'm getting 500 Internal Server Error.

Update2

The internal error was due to [HttpPost] attribute which I changed to [WebMethod] and it works.

I think the problem is in your url .

Use a leading slash(/) like following.

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

Your server side call must be static public. https://msdn.microsoft.com/en-us/library/bb398998(v=vs.90).aspx

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

I assume you are not passing any parameter. So can you try Data:{} instead of Data:"{}".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM