简体   繁体   中英

Server does not receive data from ajax call

I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.

There's the method called GetStatus(string statusText) which need to receive the content.

Here's the javascript code:

$("#btnSaveStatus").on("click", function () {
                    var statusText = $(".textareaEdit").val();

                    $.ajax({
                        type: "GET",
                        url: "Default.aspx/GetStatus",
                        data: "{statusText:'" + statusText + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
//                            $('#littlbioID').text(result.d);
                        }
                    });
                });

Please advise. You should also know that I'm new into web development.

  1. You can't have a request body in a GET request, you have to use a POST request for that
  2. The string you are constrcting is not valid JSON since:
    • Property names must be strings
    • You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON

Generate your JSON programatically.

{
  type: "POST",
  url: "Default.aspx/GetStatus",
  data: JSON.stringify({
    statusText: statusText
  }),
  // etc

Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.

Try this:

$("#btnSaveStatus").on("click", function () {
                    var statusText = $(".textareaEdit").val();
                    var jsonText = new Object();
                    jsonText.statusText = statusText;

                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/GetStatus",
                        data: JSON.stringify(jsonText);,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (result) {
//                            $('#littlbioID').text(result.d);
                        }
                    });
                });

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