使用jQuery / ajax从外部网站获取特定元素 [英] Getting specific element from external site using jQuery / ajax

查看:160
本文介绍了使用jQuery / ajax从外部网站获取特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery和 此插件

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

使用以下代码可以提高效果:

It works great using the following code:

$.ajax({
       url: 'http://www.somesite.com/',
       type: 'GET',
       success: function(res) {
          $("#here").html(res.responseText);
       }
     });

但我真正想做的只是从目标网站,我明白这只能使用 load()方法,而不是 GET

But what I would really like to do, is only pull a section (div) from the target site, and I understand this is only possible when using the load() method, not GET.

然后我找到 此代码 ,但是当我尝试将其构建到代码中时,它似乎无法正常工作,因为:

I then found this code , but when I tried to build it into the code, it didn't seem to work, as such:

$.ajax({
       url: 'http://www.somesite.com/',
       type: 'GET',
       success: function(res) {
          $(res).find('div.content').each(function(){
              $('#here').append($(this).html());
         });

       }
     });

查看Firebug上的请求,请求似乎成功,但是代码似乎不能在目标网站上找到以下标记:< div class =content row>

Looking into the request on Firebug, the request does seem successful, but the code can't seem to find the following tag: <div class="content row"> on the target site.

我需要确保目标元素有#ID而不是类吗?

Do I need to make sure the target element has an #ID, instead of a class?

谢谢!

推荐答案

在你的原始成功回调中你从responseText获取你的html内容,你应该在第二种情况下:

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

使用class =content或id应该可以工作。但是,您应该知道上面的代码将所有具有类内容的 div 添加到您的id =herediv中,这可能不是您想要的。如果只想查看特定元素的内容,请改用 id

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.

这篇关于使用jQuery / ajax从外部网站获取特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆