最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Get innerhtml from external page with Javascript - Stack Overflow

programmeradmin4浏览0评论

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?

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

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?

    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
Share Improve this question edited Nov 19, 2011 at 21:41 andriy asked Jan 18, 2011 at 20:10 andriyandriy 4,1649 gold badges50 silver badges72 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 6

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

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

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

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

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

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

 $(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();
     }
   });
 });

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

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

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

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 id is the div's id. so you would have something like :

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]);}
);

发布评论

评论列表(0)

  1. 暂无评论