【问题标题】:How do I filter body html the returned data from ajax?如何过滤body html从ajax返回的数据?
【发布时间】:2012-12-21 19:16:30
【问题描述】:

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

非常感谢您的建议。

【问题讨论】:

  • 数据的价值是什么?返回的标记是否有效?
  • 是的,data的值是正确的,整个加载的html
  • 请发布您从 GET 请求中获得的确切信息。 $(data).find('[ref=A]').html(); 应该可以工作!
  • 如果您需要过滤数据响应,数据可能已损坏,您最好使用 json 响应
  • @直到您为此使用 XHR 预加载新文档,然后您将在正文中应用,或者您只是想提取 XHR 数据结果的某些部分?我的示例适用于两者,但如果您要附加完整的文档,有更好的方法,我可以展示如何。

标签: javascript jquery jqxhr


【解决方案1】:

您可以使用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 中看到的那样,您的性能会下降很多。

【讨论】:

  • 非常感谢,我试试这个。
  • 我已经为你修复了这个例子@Till
【解决方案2】:
$("[ref=B]").append($(data).find("[ref=A]"));

你在问题​​中的做法,最后一部分find( '[ref=A]' ) 没用。

[编辑]另外,另一个问题已经超过 2 年了。对于最新版本的 jQuery,您可能需要额外的引号:

$("[ref='B']").append($(data).find("[ref='A']"));

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2011-09-16
    • 1970-01-01
    • 2015-08-06
    • 2016-01-24
    相关资源
    最近更新 更多