javascript 如何在 jQuery ajax 请求中获取 HTML 网页的一部分?换句话说,如何在 ajax 调用中过滤网页内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18749626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:05:01  来源:igfitidea点击:

How to get a part of HTML webpage in a jQuery ajax Request? In other words how to filter the web page contents on an ajax call?

javascriptjqueryajax

提问by Mike

I am using the below script to load the html in my page. However it loads all of the page contents that is included in webpage.html means(from doctype to closing html tag).

我正在使用以下脚本在我的页面中加载 html。然而,它加载了包含在 pages.html 中的所有页面内容(从 doctype 到关闭 html 标签)。

$(function() {
            $.ajax({
                type:"GET",
                url:"webpage.html",
                dataType:"html",
                success:function(data) {
                    alert(data);
                    $("body").html(data);
                },
                error:function() {
                    alert("Error");
                }
            })
        });

I have no control over webpage.html, I actually just need a few divs with particular classes to load after an ajax Request. Can anyone give me some Idea as to how would I filter the webpage contents over an ajax Call for which I have no control.

我无法控制webpage.html,实际上我只需要在ajax请求之后加载一些带有特定类的div。任何人都可以给我一些关于如何通过我无法控制的 ajax 调用过滤网页内容的想法。

Thanks, Mike

谢谢,迈克

回答by maximkou

 success:function(data) {
     var out = "";
     $(data).find("your selectors").each(function(loop, item){
         out += $(item).html();
     });
     data = out;
     alert(data);
     $("body").html(data);
 }

回答by Jonny Sooter

Use .load()

利用 .load()

var url = "webpage.html .classOfDivsYouWantLoaded";

$("body").load(url, function(){
    //callback after your data is in loaded into body.
});