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

前端 未结 5 954
忘掉有多难
忘掉有多难 2020-11-27 12:30

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

My codes: HTML:


    
相关标签:
5条回答
  • 2020-11-27 13:00

    Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:

    $.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.

    or let jQuery filter it for you:

    $('#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.

    0 讨论(0)
  • You can use JQuery .load() method:

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

     $( "#content" ).load( "ajax/test.html div#content" );
    
    0 讨论(0)
  • 2020-11-27 13:09

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

    like this:

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

    Simple!

    0 讨论(0)
  • 2020-11-27 13:09
    $.ajax({
      url:href,
      type:'get',
      success: function(data){
       console.log($(data)); 
      }
    });
    

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

    You can use JavaScript:

    var doc = document.documentElement.cloneNode()
    doc.innerHTML = data
    $content = $(doc.querySelector('#content'))
    
    0 讨论(0)
  • 2020-11-27 13:10

    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());
            }
    });
    
    0 讨论(0)
提交回复
热议问题