Getting specific element from external site using jQuery / ajax

前端 未结 2 1085
执笔经年
执笔经年 2020-12-06 12:11

I am using jQuery and this plugin to pull content from an external site.

It works great using the following code:

$.ajax({
       ur         


        
相关标签:
2条回答
  • 2020-12-06 12:37

    In your original success callback you're fetching your html contents from responseText, you should do the same in the second case:

       success: function(res) {
          $(res.responseText).find('div.content').each(function(){
              $('#here').append($(this).html());
         });
    

    Using class="content" or id should work. However, you should be aware that the code above adds all div's that have class content to your id="here" div, which might not be what you want. If you want just the contents of a specific element, use its id instead.

    0 讨论(0)
  • 2020-12-06 12:57

    Try using jQuery.parseHTML();

    Description: Parses a string into an array of DOM nodes.

    $.ajax({
       url: 'http://www.somesite.com/',
       type: 'GET',
       success: function(res) {
          var data = $.parseHTML(res);  //<----try with $.parseHTML().
          $(data).find('div.content').each(function(){
              $('#here').append($(this).html());
         });
    
       }
     });
    

    because ajax response is a string and that way you can't use .find() method to find a dom node. so first you have to parse the string as dom nodes which you recieved from server then you can use .find() to select your target element.

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