ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 如何从ajax过滤返回数据的正文html?

2019-05-29 19:22:20  阅读:249  来源: 互联网

标签:jquery javascript 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返回的数据中过滤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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有