Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery cannot retrieve data from localhost

I have a very simple bit of jQuery to retrieve my latest Tweet

$.getJSON("http://twitter.com/statuses/user_timeline/username.json?count=1", 
           function(data) {
              $("#tweet_text").html(data[0].text);
           });

This works fine on a simple HTML file on my desktop. However, once the file is accessed from my localhost (apache) no data is being returned. I was wondering if any part of Apache was blocking the request somehow? Or any other ideas?

like image 655
fatnic Avatar asked Jul 11 '26 12:07

fatnic


1 Answers

JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy.

You're best bet is probably to look into JSONP for this.

You can find more information on it from both jQuery:

If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

and Twitter:

Parameters:

  • callback: Optional. Only available for JSON format. If supplied, the response will use the JSONP format with a callback of the given name.

    • Example: http://search.twitter.com/search.json?callback=foo&q=twitter

Hope this helps.


Correction...

If status/user_timeline supports JSONP, it's not documented as such.

You may have to look into setting up a Cross-Domain Proxy to get the data you want.

like image 118
Jonathan Lonowski Avatar answered Jul 13 '26 09:07

Jonathan Lonowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!