2013-01-08 34 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