javascript – 如何从ajax过滤返回数据的正文html?
作者:互联网
我的目的是,我想从数据中取出特定的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>
我的问题是,是否有一个解决方案来从$.ajax返回的数据中过滤body的html?喜欢
body_html = $(data).???????
然后我可以做任何我想做的事,比如
body_html.find('xxxx');
非常感谢您的建议.
解决方法:
您可以使用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中所看到的,您的性能将会下降很多.
标签:jquery,javascript,jqxhr 来源: https://codeday.me/bug/20190529/1180110.html