gpt4 book ai didi

javascript - 如何过滤 body html 从 ajax 返回的数据?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:36:31 25 4
gpt4 key购买 nike

我的目的是,我想从数据中取出特定的 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 返回的数据中过滤正文的 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 中看到的那样,你的成绩会下降很多。

关于javascript - 如何过滤 body html 从 ajax 返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14206467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com