jQuery 如何使用jQuery ajax在另一个页面上获取div的html?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18938180/
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-08-26 22:49:11  来源:igfitidea点击:

How to get the html of a div on another page with jQuery ajax?

javascriptjqueryhtml

提问by Iago Bruno

I'm using jQuery's ajax code to load new pages, but wanted him to get only the html of a div.

我正在使用 jQuery 的 ajax 代码加载新页面,但希望他只获取 div 的 html。

My codes: HTML:

我的代码: HTML:

<body>
    <div id="content"></div>
</body>

Script:

脚本:

$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html(data);
   }
});

I wanted him to get only the html of $('div#content') on another page. How to do it?

我希望他在另一个页面上只获取 $('div#content') 的 html。怎么做?

回答by Gustavo Costa De Oliveira

Ok, You should "construct" the html and find the .content div.

好的,您应该“构建”html 并找到 .content div。

like this:

像这样:

$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html($(data).find('#content').html());
   }
});

Simple!

简单的!

回答by nilgun

You can use JQuery .load() method:

您可以使用 JQuery .load() 方法:

http://api.jquery.com/load/

http://api.jquery.com/load/

 $( "#content" ).load( "ajax/test.html div#content" );

回答by Sinisha Mihajlovski

If you are looking for content from different domain this will do the trick:

如果您正在寻找来自不同域的内容,这可以解决问题:

$.ajax({
    url:'http://www.corsproxy.com/' +
        'en.wikipedia.org/wiki/Briarcliff_Manor,_New_York',
        type:'GET',
        success: function(data){
           $('#content').html($(data).find('#firstHeading').html());
        }
});

回答by adeneo

You really can't do that, an ajax request gets the entire file, but you can filter the content once it's retrieved:

你真的不能那样做,ajax 请求会获取整个文件,但是你可以在检索到内容后对其进行过滤:

$.ajax({
   url:href,
   type:'GET',
   success: function(data) {
       var content = $('<div>').append(data).find('#content');
       $('#content').html( content );
   }
});

Note the use of a dummy element as find()only works with descendants, and won't find root elements.

请注意,虚拟元素的使用find()仅适用于后代元素,不会找到根元素。

or let jQuery filter it for you:

或者让 jQuery 为您过滤它:

$('#content').load(href + ' #IDofDivToFind');

I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.

我假设这不是跨域请求,因为这不起作用,只有同一域上的页面。

回答by zangbianxuegu

$.ajax({
  url:href,
  type:'get',
  success: function(data){
   console.log($(data)); 
  }
});

This console log gets an array like object: [meta, title, ,], very strange

这个控制台日志得到了一个像 object: [meta, title, ,] 这样的数组,很奇怪

You can use JavaScript:

你可以使用 JavaScript:

var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))