1

我试图找出如何查看 AJAX 请求是否返回错误。用于测试请求总是返回<p id="error">test</p>

我以为你可以这样做:

//html is the var which contains the result
var DOM = $(html);
if( $('#error', DOM ).length != 0 ) {
    alert(html);    
}

但这不起作用。任何人都可以对出了什么问题有所了解吗?

4

4 回答 4

2

如果您的 HTML 没有包含在某些东西(例如 a div)中,那么它需要包含在内。

var html = '<div></div><p id="error">ERROR!</p><span>other stuff</span>';

var DOM= $('<div>' + html + '</div>');
if( $('#error', DOM).length != 0 ) {
    alert(html);    
}

示例:http: //jsfiddle.net/jonathon/exqTD/

(我认为wrap在这里会有所帮助,但事实并非如此。如果有人知道为什么,请指出)。

或者,选择器上下文是使用find实现的,所以你可以这样做:

if( DOM.find('#error').length != 0 ) {
    alert(html);    
}
于 2011-01-07T09:49:30.953 回答
1

It is not inserted to the DOM, so you cannot look it up with a selector.

You could try to use a simple regex with the test() function on the variable.

if (html.test(/id="error"/i)) {
   ...
}
于 2011-01-07T09:40:20.950 回答
0

检查这是否有帮助:

$('body').append('<div class="hidden_div">'+html+'</div>');
if($('#error',$('.hidden_div')).size()>0){
  alert(html);
}

只需添加css

.hidden_div{display:none;}

应该就是这样,哦,你可以使用.length.size()

或者你可以使用:

if(html.indexOf('id="error"')>-1){alert('yes we have an error!');}

干杯

G。

于 2011-01-07T09:45:55.660 回答
0

您可以使用查找功能:

if ( $(html).find("#error").length != 0 )
{
    alert(html);    
}
于 2011-01-07T09:46:26.753 回答