Get innerhtml from external page with Javascript

前端 未结 6 565
离开以前
离开以前 2021-02-04 17:47

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?

    

        
相关标签:
6条回答
  • 2021-02-04 17:53

    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 讨论(0)
  • 2021-02-04 17:58

    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();
     });
    
    0 讨论(0)
  • 2021-02-04 17:59

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

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

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

    0 讨论(0)
  • 2021-02-04 18:00

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

    0 讨论(0)
  • 2021-02-04 18:04

    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();
         }
       });
     });
    
    0 讨论(0)
  • 2021-02-04 18:04

    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.

    0 讨论(0)
提交回复
热议问题