问题描述:

I am trying to make mechanism for respond with custom http status messages and to catch it in the client side with jQuery Ajax.

I figured out a way to do only for error messages (HTTP 4xx, 5xx), but not for the success http messages (HTTP 2xx).

As example I managed to extract and alert 'FROG CATCH' from HTTP 400 FROG CATCH status, but can't alert 'FROG ESCAPE' from HTTP 200 FROG ESCAPE

Does any body knows a way to extend jQuery ajax for supporting that kind of schema?

Anyone?

网友答案:

AJAX responses are based on success and error. If your content returns with a 200 status (OK), 304 (not modified), etc... then the AJAX call will utilize your success response section, not your error section where status is typically displayed (status in the error section is primarily used to indicate the reason for the error). Depending on what you're returning and what format you're returning it in, you should be looking in the success section for that response. Assuming your server language is PHP, you might include that success status in the returned data (converted to a JSON object for parsing), like so:

$.ajax({
    url : 'your_url.php',
    type : 'POST',
    dataType : 'JSON',
    data : yourData,
    success : function(data) {
        if(data) {
            if(data.status) {
                alert('Status: ' + data.status);
            }
        }
    },
    error : function(xhr, response, status) {
        alert('Response: ' + response.responsetext);
    }
});

By utilizing your JSON object as the status carrier, you can customize your status response. As to seeing what the actual server header response is, this would be listed in the network tab in Chrome inspector, net tab in Firebug, or Safari's development tool section (I forget the name offhand).

相关阅读:
Top