Javascript 如何使用 AJAX 从不同页面获取 div 的 html?

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

How to get the html of a div from a different page with AJAX?

javascriptjqueryajax

提问by Mike Burnwood

How can I get the html of a certain html element which is located on a different site?

如何获取位于不同站点上的某个 html 元素的 html?

Solution:

解决方案:

$.ajax({
url: 'somefile.html',
success: function(data) {
    data=$(data).find('div#id');
    $('#mydiv').html(data);
    alert('Done.');
 }
});

采纳答案by user1415567

Make a ajax call to a php or any other file , use CURL or other tools to grab the page you want and extract the div and echo it and then when you get back the html just put it inside a div in your page

对 php 或任何其他文件进行 ajax 调用,使用 CURL 或其他工具抓取您想要的页面并提取 div 并回显它,然后当您返回 html 时,只需将其放入页面中的 div 中

    $.ajax({
    url: 'somefile.html',
    success: function(data) {
                    data=$(data).find('div#id');
        $('#mydiv').html(data);
        alert('Done.');
     }
    });

回答by Norse

You can use $.loadwith an appended container

您可以将$.load与附加容器一起使用

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted.

.load() 方法与 $.get() 不同,它允许我们指定要插入的远程文档的一部分。

$('#result').load('ajax/test.html #container');

回答by gopi1410

Here you go:

干得好:

$('#div_id_in_your_page').load('ajax_page.html #required_div');

For class:

上课:

$('.div_class_in_your_page').load('ajax_page.html #required_div');

回答by Mich Dart

One way is:

一种方法是:

  • send an ajax call to a server side script

  • this script fetches the remote page and returns HTML as a response. (generally JSON is preferred)

  • your page finally gets access to the html.

  • 向服务器端脚本发送 ajax 调用

  • 此脚本获取远程页面并返回 HTML 作为响应。(通常首选 JSON)

  • 您的页面终于可以访问 html。

回答by John Rey Flores

you can also use like this.

你也可以这样使用。

$.ajax({
   url:"page2.html",
   success:function(response){
      $("#currentDIV").html(response);
   },error:function(){
      alert("error");
   }
});