开发者

Load text from specific external DIV using AJAX?

开发者 https://www.devze.com 2023-01-02 14:47 出处:网络
I\'m trying开发者_如何学JAVA to load up the estimated world population from http://www.census.gov/ipc/www/popclockworld.html using AJAX, and so far, failing miserably.

I'm trying开发者_如何学JAVA to load up the estimated world population from http://www.census.gov/ipc/www/popclockworld.html using AJAX, and so far, failing miserably.

There's a DIV with the ID "worldnumber" on that page which contains the estimated population, so that's the only text I want to grab from the page.

Here's what I've tried:

  $(document).ready(function(){
    $("#population").load('http://www.census.gov/ipc/www/popclockworld.html #worldnumber *');
  });


What you are trying to do is known as a cross-domain request. This is not a feature that browsers normally allow (security feature). Some ways to get around this limitation are described here: The jQuery Cross-Domain Ajax Guide.


you can try something like this:

$.get('http://www.census.gov/ipc/www/popclockworld.html', function(content) {
    $("#population").html($('#worldnumber',$(content)));
});


Yeah, it's security. You can't ajax in to pages that aren't from the same domain.


@R0MANARMY:

I couldn't seem to follow the directions given on that site you linked to, but I did figure out a solution... I created a PHP file with the following code:

//Run cURL call
$ch = curl_init('http://www.census.gov/main/www/rss/popclocks.xml');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

//Set as new XML object
$doc = new SimpleXmlElement($data, LIBXML_NOCDATA);


function parseRSS($xml) {
  $cnt = count($xml->channel->item);
  for($i=0; $i<$cnt; $i++) {
    $title = $xml->channel->item[$i]->title;
    if ( preg_match("/world population estimate:\s([0-9,]+)\s/i", $title, $match) ) {
      echo $match[1];
    }
  }
}

parseRSS($doc);

Then I called it with jQuery like so:

<div id="population"></div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#population').load('getpop.php');
    var refreshId = setInterval(function() {
      $('#population').load('getpop.php');
    }, 120000);
   });
</script>

Just thought I'd post it here in case anyone else is looking to do something similar.

0

精彩评论

暂无评论...
验证码 换一张
取 消