简体   繁体   中英

Does an AJAX call with jQuery have to return data?

On my little server I have a POST method called /assign. It takes some form parameters and simply returns 200 for success and other error codes for when something goes wrong -- no json or html or text or anything else.

I wrote an ajax call using jQuery. It looks like this:

var formData={};
formData["vm-name"]=$("input#vm-name").val();
formData["vm-address"]=$("input#vm-address").val();

$.ajax({
url: "/api/redirects",
    type: "POST",
    data: formData,
    success: function(){
        window.location.href="/current";
    },
    error: function(data, textStatus, jqXHR){
        permitSubmission();
        errorMessage(["Network error. Try again."])
    }
});

On my server the data is accepted, the method executes, and it returns a 200. In Chrome, the network inspector shows the request as returning with a 200 code. However, the error function is always called; the textStatus variable is something like "parseerror". Some Googling suggests this is due to not being able to parse the returned data (which makes sense since there's no returned content.)

So, is there a way to ignore the lack of content?

EDIT: I'd like to be able to have no return content, not modify the server so it returns JSON or something.

Does an AJAX call with jQuery have to return data?

Yes, however, consider that the lack of data is also data. If your server is returning the application/json content type, then the returned data must match that content type. Examples of valid lack of data for application/json is {} , [] , or null , not empty string. Therefore, if the current contentType is application/json, you must return one of the aforementioned three, or, change the contentType to something else that can be an empty string, such as text/plain .

You could try defining the datatype your request should return:

$.ajax({
url: "/api/redirects",
type: "POST",
data: formData,
dataType: "text",
success: function(){
    window.location.href="/current";
},
error: function(data, textStatus, jqXHR){
    permitSubmission();
    errorMessage(["Network error. Try again."])
}
});

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