简体   繁体   中英

Internal Server Error returning from C# WebMethod to JavaScript AJAX call

I can't get the AJAX call to get the return from the C# WebMethod. It always returns the AJAX error "Internal Server Error".

A button calls JS function:

<button id="btn" onclick="Create();">foo</button>

The JS function:

function Create() {
var data = {
    value1: 'string 1',
    value2: 'string 2',
    value3: 'string 3'
};
$.ajax({
    url: 'default.aspx/Create',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ formData: data }),
    async: true,
    success: function (msg, status) {
        alert("success " + msg.d);
    },
    failure: function (data) {
        alert("failure " + msg.d);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus + " : " + errorThrown);
    }
  });
return false;
}

And the C# WebMethod:

[WebMethod]
public static string Create(string data)
{
    return "webmethod string";
}

Can anyone point me where is the mistake?

You are returning a string but the success method is expecting json. Ajax doc here: http://api.jquery.com/jquery.ajax/

Datatype property:

dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback)

Change datatype to "text"

Also chnage your paramater from "formData" to "data"

code:

$.ajax({
    url: 'default.aspx/Create',
    type: 'POST',
    dataType: 'text',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ data: data }),
    success: function (data) {
        alert("success " + data);
    },
    failure: function (data) {
        alert("failure " + msg.d);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus + " : " + errorThrown);
    }
  });

3:d edit here: you are sending an object in you ajax call but your paramater on server side is a string. change it to a class instance with the same name properties as the object that you are sending

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