如何过滤从ajax返回的html正文? [英] How do I filter body html the returned data from ajax?

查看:178
本文介绍了如何过滤从ajax返回的html正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目的是,我想从数据中提取特定的html并仅更新该区域.

My purpose is, I want to take specific html out from data and update that area only.

如何从jQuery过滤返回的数据.ajax?

此链接是旧帖子,但我确实有完全相同的问题.

This link is a old post but I do have the exactly same problem.

链接提供的解决方案是$("[ref=B]").html(data).find( '[ref=A]' );

The solution giving from the link is $("[ref=B]").html(data).find( '[ref=A]' );

但是,如果我这样做的话,整个页面将首先写在<span ref='B'>上,然后在其中找到选择器.....

However, if I do so, the entire page will write on <span ref='B'> first then find the selector inside of it.....

仅找到'[ref = A]'的另一种方法是

The alternative way to only find '[ref=A]' is

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返回的数据中过滤主体的html?喜欢

My question is, is there a solution to filter body`s html from data which returned from $.ajax?? like

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

然后我可以做任何我想做的事,例如

then I can do whatever I want, like

body_html.find('xxxx');

非常感谢您的建议.

推荐答案

您可以使用

You can use a DocumentFragment to simulate your html and do your search without appending it to the 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')中进行过滤,但是正如您在 测试 ,您的效果会下降很多.

You also can do a filter in jQuery templating $(data).filter('.foo') but as you can see in this tests, your performance will drop a lot.

这篇关于如何过滤从ajax返回的html正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆