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

标签 javascript jquery jqxhr

我的目的是,我想从数据中取出特定的 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/

相关文章:

javascript - 防止通过双击执行两次 jQuery post 请求

Javascript toLowerCase() 性能与变量创建

javascript - 无法在 Google Chrome 扩展程序中获取正确的 Ace 编辑器文本

javascript - Moxtra 聊天 SDK 时间线(完整 View )

javascript - 创建一个 Web 应用程序,向用户提交的电话号码发送标准短信

javascript - jquery $.get 分配给变量的结果在事件监听器中不可用

javascript - 如何让一个网页显示在另一个网页中?

jquery - 如何使用 jQuery 和 xhr2 进行文件上传(返回空 $_FILES)

javascript - CORS 飞行前返回 Access-Control-Allow-Origin :*, 浏览器仍然失败请求

jquery - Rails 中的 jqXHR 与 jQuery AJAX 请求