简体   繁体   中英

Sending ajax POST request receiving GET request

I'm using the following ajax code:

$.ajax({
    url: "Editor.aspx/Page_LoadComplete",
    data: { "contentCheckCode": contents },
    type: "POST",
    success: function (response) {
        alert("Contents saved...");
    },
    error: function (xhr, status, errorThrown) {
        alert("Error: " + errorThrown);
    }
});

to send a post request to the code behind my webpage in order to save the contents of my tinyMCE editor to a file. My problem is that the code behind isn't receiving a POST request but rather a GET request, the following C# code highlighted this issue and also that the request had no contents:

protected void Page_LoadComplete(object sender, EventArgs e) {
string test =Request.HttpMethod;
//listens for POST request
if (Request.HttpMethod == "POST"||Request.HttpMethod=="GET")
{
    String requestContents;
    using (Stream inputStream = Request.InputStream)
    {
        using (StreamReader readStream = new StreamReader(inputStream))
        {
            requestContents = readStream.ReadToEnd();
        }
    }
}

Any suggestions as to how to resolve this? I've searched for answers but can't seem to find anyone who had similar issues. I'm sure there's something I've done wrong or missed as I'm new to both jQuery and C#

Also as a new user on Stack Exchange I can't include images in my posts yet, but I tried to use the Network tab of the Chrome developer tools to shed some light on what was happening, the output of which can be found here: http://imgur.com/2LHuch8

EDIT: changed my ajax code to the following:

$.ajax({
            url: "Editor.aspx/PostHandle",
            data: { "content": contents },
            dataType: "text",
            type: "POST",
            success: function (response) {
                alert("Contents saved...");
            },
            error: function (xhr, status, errorThrown) {
                alert("Error: " + errorThrown);
            }
        });

and added the following method to my code behind:

[WebMethod]
    public static String PostHandle(String content) {
        String test = content;
        return "Hello world";   
    }

and I placed a breakpoint at the above method but it's still not catching the request, is there something I'm missing?

Your webmethod should be having the syntax:

[WebMethod]
public static string Page_LoadComplete(int id)
{
    ....
    return "hello";
 }

and similarly your ajax call:

$.ajax({
    type: "POST",
    url: "YourPage.aspx/Page_LoadComplete",
    data: "{'id':'1'}",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        //do something with 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