简体   繁体   中英

ajax GET works, POST gives 400 error

GetData(...) method was OK, but SetSimple(...) method throwing error 400.

Javascript:

$.ajax(url,
        {
            type: action,
            timeout: 3000,
            data: { value: 123 },
            contentType: "application/json; charset=utf-8",
            //dataType: "json",
            success: function (data, textStatus, jqXHR) {
                displayInfo("success: "+data);
            },
            error: function(jqXHR, textStatus, errorThrown ) {
                displayInfo("error: "+errorThrown+" "+textStatus);
            }
        }
   );

C#:

[WebGet(RequestFormat = WebMessageFormat.Json)]
    string GetData(int value);

[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
    string SetSimple(int value);

To run/test it I have the service opened in a browser, then my test page with the javascript in another browser. (And dataType: "json" doesn't seem to help.) And the fiddler response shows "The server encountered an error processing the request. See server logs for more details", but I don't see anything in the Event Logs. Anyone see if/what I'm doing wrong?

You should be transform your JavaScript object into string.

JSON.stringify(data)

Then on your example

$.ajax (url,
    {
        type: action,
        timeout: 3000,
        data: JSON.stringify({ value: 123 }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            displayInfo("success: "+data);
        },
        error: function(jqXHR, textStatus, errorThrown ) {
            displayInfo("error: "+errorThrown+" "+textStatus);
        }
    }

);

Your ajax request is setting the "data" property to { value: 123 }. You need to pass the appropriate object to the SetObject method which is CompositeType. The ajax request looks like you're using it as a utility function so just pass data as a parameter so the ajax request would be:

    var makeAjaxCall = function(url, action, data) {
        $.ajax(url,
            {
                type: action,
                timeout: 3000,
                data: data,
                contentType: "application/json; charset=utf-8",
                success: function (data, textStatus, jqXHR) {
                    displayInfo("success: "+data);
                },
                error: function(jqXHR, textStatus, errorThrown ) {
                    displayInfo("error: "+errorThrown+" "+textStatus);
                }
            }
       );
    }

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