everyone. I have following example script:
<script type="text/javascript">
$(document).ready(function() {
var url = "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";
$.getJSON(url + "?callback=?", null, function(tweets) {
for(i in tweets) {
tweet = tweets[i];
$("#tweet-list").append(tweet.text + "<hr />");
}
});
});
</script>
Now I want to refresh the data gotten from the url when clicked. I added a global variable ‘content’ and tried:
<script type="text/javascript">
$(document).ready(function() {
$("body").click(function(){
var content="";
var url = "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";
$.getJSON(url + "?callback=?", null, function(tweets) {
for(i in tweets) {
tweet = tweets[i];
content+=tweet.text + "<hr />";
}
});
$("#tweet-list").html(content);
});
});
</script>
But it showed nothing, then I thought maybe that’s because ‘$(“#tweet-list”).html(content);’ executed before ‘content+=tweet.text + “
“‘, so i tried to add a callback function after():
<script type="text/javascript">
$(document).ready(function() {
$("body").click(function(){
var content="";
var url = "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";
$.getJSON(url + "?callback=?", null, function(tweets,after) {
for(i in tweets) {
tweet = tweets[i];
content+=tweet.text + "<hr />";
}
after(content){$("#tweet-list").html(content);};
});
});
});
</script>
still not working (showing nothing), any help? thx.
Ajax is asynchronous, so you’ll have to wait for a response and some data to come back before you can do anything with it. When you’re trying to use the content after the ajax function, it’s not done yet, and there is no content. You’ll have to do that inside the callback when there is actual content to append and the ajax call is completed :