最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if an AJAX response has HTML contents in jQuery? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jul 25, 2013 at 17:34 keeehlankeeehlan 8,05416 gold badges58 silver badges105 bronze badges 5
  • 2 Do you know the exact response on success, if so - you could check for success instead, and then assume html/failure if it is not. – Jacob Oettinger Commented Jul 25, 2013 at 17:37
  • 1 Well, if one only returns a status code, if(response.indexOf('<') > -1) because status codes don't have < but html does. – Ohgodwhy Commented Jul 25, 2013 at 17:39
  • It's not a best practice at all...but the way you're sending it back isn't either. I'd send back echo json_encode(array('success' => true, 'html' => '<html stuff>')) when successful, otherwise, echo json_encode(array('success' => false)) when not successful and check if resonse.success !== false – Ohgodwhy Commented Jul 25, 2013 at 17:42
  • Ok. And you do not know enough about the status code without html to be able to recognise that one? (or just do as Ohgodwhy says). And yes, you would be cleaner to make the API always return json, with the html in the json response if needed. – Jacob Oettinger Commented Jul 25, 2013 at 17:42
  • Sorry for the PHP, poor assumption on my part. Looks like Andre has it in the answer. – Ohgodwhy Commented Jul 25, 2013 at 17:45
Add a comment  | 

1 Answer 1

Reset to default 24

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 ) {
        ...
    }
}
发布评论

评论列表(0)

  1. 暂无评论