Pergunta

I have the following call:

var params={type:"PUT", dataType:"application/json; charset=UTF-8", url:"api/servletpat", data:JSON.stringify(dataObject)};
$.ajax(params)
    .done(function(data, status, jqXHR){
        successCallback(data);
    })
    .fail(function(jqXHR, status, thrown){
        if (jqXHR.status == 200){
            successCallback(null);
        }
    });

Although the server does send a JSON response, ajax executed the .fail case with jqXHR.status = 200. Which means the returned data is not accessible. I cannot use "GET" because GET encodes the submitted object in the URL and this is not acceptable. What do I need to do to be able to read the returned JSON object ? Thanks...

Foi útil?

Solução

You are specifying an invalid value for the dataType setting. This causes the .fail callback to get called (instead of the .done callback), even though the jqXHR.status is 200. The second parameter to the .fail callback function (the "textStatus" parameter) will be "parsererror".

jsfiddle demo that fails

You should have:

contentType: "application/json; charset=UTF-8",
dataType: "json",

jsfiddle demo that succeeds

With the contentType setting, you are specifying the content-type for the ajax request. When you set dataType to "json", you are telling jQuery that the response will be JSON. That causes jQuery to automatically parse the response into an object (or array or null) before passing it as the data parameter to the .done callback function.

Outras dicas

status 200 means OK, not that the data is not accessible http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

TYPE has to be either GET or POST

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top