2013-01-08 28 views
4

我的目的是,我想从数据中提取特定的html并仅更新该区域。如何从ajax过滤body html返回的数据?

How do I filter the returned data from jQuery.ajax?

这个链接是一个老的文章,但我有完全相同的问题。

该解决方案从链接给为$("[ref=B]").html(data).find('[ref=A]');

但是,如果我这样做,整个页面会写上<span ref='B'>第一然后找到它里面选择.....

的替代方法只找到 '[REF = A]' 是

html = $(data).filter('[ref=B]').find('[ref=A]').html() // this way will work 

没有这些将工作

$(data).find('[ref=A]').html(); 
$(data).filter('[ref=A]').html(); 
$(data).filter('body').html(); 
$(data).find('body').html(); 

HTML

`<body> 

<span ref='B'><span ref='A'>abc</span></span> 

</body>` 

JS

$(function() { 
$.get(window.location.pathname + window.location.search, function(data){ alert(data);}); 
}); 

返回的数据

<html> 
<body> 
    <span ref='B'><span ref='A'>abc</span></span> 
</body> 
</html> 

我的问题是,有没有从从$就返回的数据过滤body`s HTML的解决方案? ?像

body_html = $(data).??????? 

话,我可以做我想做的事情,像

body_html.find('xxxx'); 

非常感谢你的建议。

+1

数据的价值是什么?是否返回有效的标记? – whitneyit

+0

是的,数据的值是正确的,整个加载的html – Till

+1

请发布你从GET请求得到什么。 '$(data).find('[ref = A]')。html();'应该工作! – undefined

回答

4

您可以使用DocumentFragment来模拟您的html,并执行您的搜索,而不追加到DOM

// Create your DocumentFragment to be able to work without DOM 
var body_html = document.createDocumentFragment(); 

// Convert and append data from your jQuery to work with fragment 
body_html.appendChild($(data)[0]); 

// Now you can select using your jQuery 
var $body_html = $(body_html); 

// Now you can use the find or whatever you want, like if it was in the DOM 
$body_html.find('.foo'); 

// Or you can append in your current document, 
// but attention, after it the fragment reference is erased 
$body_html.appendTo(document.body); 
// now you need to get reference again from body, 
// because your fragment doesn't exists anymore. 

// So... if you try: 
console.log(body_html); // undefined 
console.log($body_html); // jquery over undefined, probably just a jquery useless 

// At this point you will need to reference from DOM to continue manipulation 
$body_html = $(document.body); 
// Now I'm ready to continue the work 
// This var is like your DocumentFragment, but already on DOM. 

你也可以做jQuery的模板$(data).filter('.foo')过滤但你可以在这个tests看,你的表现会下降很多。

+0

非常感谢,我会试试这个。 – Till

+0

我已经为您修复了示例@Till –

2
$("[ref=B]").append($(data).find("[ref=A]")); 

你这样做在你的问题,最后部分find('[ref=A]')是没用的。

另外,另一个问题是2岁以上。对于最新版本的jQuery,您可能需要额外的引号:

$("[ref='B']").append($(data).find("[ref='A']")); 
+0

感谢您的建议 – Till