How to check if an AJAX response has HTML contents

2020-03-23 17:44发布

问题:

I have a page with one form and two possible responses in the event of a successful AJAX call, one of which only returns a status code.

What I need to do is check the response object in my success callback for any HTML contents so that I can display them on my page.

I already know that I can access response in my callback by adding it as a parameter, like so:

function success(response) { }

The only thing I can't figure out is how to check if that object has any HTML contents. How can I do this?

回答1:

You probably want to look at the response headers for an HTML MIME type. $.ajax will pass a jqXHR object back into your success callback, which you can then call .getResponseHeader() on:

function success( response, status, jqXHR ) {
    if( jqXHR.getResponseHeader('content-type').indexOf('text/html') >= 0 ) {
        ...
    }
}