简体   繁体   中英

Pull data from specific div on external site

Okay, I've seen a lot of topics hovering around this theme, but all of them I've seen involve JSON or Ajax to respond to client-side events. I don't need to do that. I just want to load data from a specific div on an external site when my page loads.

For example, say an external site http://www.example.site has the following code:

<div id="tm_score_1">
    129.5
</div>

When my own page loads, I want to be able to pull in that 129.5 value. I'm assuming it isn't as simple as using load("http://www.example.site #tm_score_1") because it's an external site, right?

You can't do this in javascript because of the same origin policy , without some server-side proxy. You could either proxy it on your server or use a proxy provided by someone else, like Yahoo (as suggested by other answers) via YQL or YQL via this plugin .

To expand on what Tentonaxe was saying about retrieving it from your server.
The idea is to have a path like

________      ________        __________
|      |     |        |      | external |
| user |     | server |      |   site   |
|______| ->  |________|  ->  |__________|
\......\     |........|      /........../
 \______\    |________|     /__________/

     \/-----<----<
                 ^ 
Javascript ->   PHP    ->  Retrieve Info -\/
                 ^<--------<--------<------

The idea is your javascript calls php on your server, which then uses curl or file_get_contents to connect to the external server and retrieve the information. This information is then passed back to the javascript from the php on your server.

(and yes, I was bored enough to do some (admittedly bad) ascii art for it).

You could use the cross domain jQuery plugin .

You then can do the following using yahoo's server as a proxy.

$('#container').load('http://google.com'); // SERIOUSLY!

$.ajax({
    url: 'http://news.bbc.co.uk',
    type: 'GET',
    success: function(res) {
        var headline = $(res.responseText).find('a.tsh').text();
        alert(headline);
    }
});

James Padolsey blogged about it here .

If the robots.txt permits, you could use YQL . Here's a query for the current version of jQuery .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM