jQuery cannot retrieve data from localhost
I have a very simple b开发者_开发问答it 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?
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.
Try appending callback=?
to the URL. Like this
"http://twitter.com/statuses/user_timeline/username.json?count=1&callback=?"
maybe it takes a bit longer for the html to load on localhost for some reason and you haven't wrapped the script in a dom ready. so it makes a call and there is no #tweet_text at that moment to get filled
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: success
});
Ajax (Non-JSONP) is not allowed to cross domains.
精彩评论