Javascript 使用Javascript从外部页面获取innerhtml

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

Get innerhtml from external page with Javascript

javascriptjqueryhtml

提问by andriy

I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?

我正在尝试获取位于外部页面上的 DIV 的 innerHTML。可以使用这种 javascript 代码来做到这一点吗?

    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>

采纳答案by generalhenry

the jquery load function allows you to specify an element id to load

jquery 加载函数允许您指定要加载的元素 ID

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

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

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

回答by scragz

Since it looks like you are using jQuery, something like this should be pretty close:

由于看起来您正在使用 jQuery,因此应该非常接近:

 var html;
 $.get("my_page.html", function(data){
     html = $(data).find('#glr1').html();
 });

回答by Pointy

You could create a hidden <iframe>element, load the page into that, and then dive into it to locate your content.

您可以创建一个隐藏<iframe>元素,将页面加载到其中,然后深入其中以找到您的内容。

 $(function() {
   $('body').append($('<iframe></iframe>', {
     css: { display: none },
     src: 'my_page.html',
     id: 'my_mage',
     load: function() {
       var html = $('#my_page').contents().find('whatever').html();
     }
   });
 });

回答by keepwalking

You cannot get the html from an external html due to security issues.

由于安全问题,您无法从外部 html 获取 html。

You can get the html only from a frame located on the same domain.

您只能从位于同一域的框架中获取 html。

回答by ChrisJ

It's possible to do what you wish, but I would say you have to retrieve the external HTML file using XMLHttpRequestfirst.

可以随心所欲,但我会说您必须首先使用XMLHttpRequest检索外部 HTML 文件。

回答by gion_13

not quite. Only if the desireed page is on the same domain and same protocol you could try to embed it in an iframe or you could use ajax. jQuery already has implemented a way to retrieve only a part of an external page ,via ajax:
$.get(url+"#"+id);, where idis the div's id. so you would have something like :

不完全的。只有当所需的页面位于相同的域和相同的协议上时,您才可以尝试将其嵌入 iframe 中,或者您可以使用 ajax。jQuery 已经实现了一种方法来仅检索外部页面的一部分,通过 ajax:
$.get(url+"#"+id);iddiv 的 id在哪里。所以你会有类似的东西:

var aux = window.location.href.split('/'),
id = 'glr1',
page = 'my_page.html';
$.get(
  aux.splice(0,aux.length-1).join('/') + '/' + page + '#' + id,
  function(){alert(arguments[0]);}
);