开发者

JSon/Jquery request with a setTimeout always returns a "null" result? (for Twitter Search API)

开发者 https://www.devze.com 2022-12-23 13:29 出处:网络
I make a call to the twitter API. 开发者_运维技巧100 posts are retreived + a properties that tells me what the next page to call is. So I wait 5 sec. and call that next page, but the JSon results in t

I make a call to the twitter API. 开发者_运维技巧100 posts are retreived + a properties that tells me what the next page to call is. So I wait 5 sec. and call that next page, but the JSon results in the callback function is always null the second time... I think it's probably a JQuery problem...

Here's the code to test it if you want :

<html>
<head>
<script type="text/javascript" src="./jquery-1.4.2.min.js"></script>
<script>
function test() {
    var rqUrl = "http://search.twitter.com/search.json?q=%23apple+OR+%23ipad&rpp=100&callback=?"
    callTwitterSearchApi(rqUrl);
}

function callTwitterSearchApi(tiwtterRequestUrl) {
    debug("request to twitter : " + tiwtterRequestUrl);

    // *** FIRST CALL WORKS GREAT... ***
    $.getJSON(tiwtterRequestUrl, callTwitterSearchApi_callback);
}

function callTwitterSearchApi_callback(jsonPostsResults) {
    debug("callback");

    if (jsonPostsResults == null) {
    debug("Why is jsonPostsResults null? If I copy paste the request inside a browser, I get something =(");
    return; 
    }

    if (jsonPostsResults.error != undefined && jsonPostsResults.error != "") {
        debug("twitter api error");
    }
    var posts = new Array();
    $(jsonPostsResults.results).each(function() {       
        posts.push(this);
    }); 

    debug("Number of posts : " + posts.length);

    if (jsonPostsResults.next_page != undefined && jsonPostsResults.next_page.trim() != "") {        
        debug("calling next request in 5 sec..."); 
            // *** WHEN COMMING BACK FROM THAT LINE, JSON RESULTS == NULL?! ****
        setTimeout("callTwitterSearchApi(\"http://search.twitter.com/search.json" + jsonPostsResults.next_page + "\")", 5000); 
    }

}

function debug(message) {
    document.getElementById('debug').innerHTML = message + "\n" + document.getElementById('debug').innerHTML;
}
</script>
</head>
<body>
<input type="button" onclick="test();" value="test" /><br />
<textarea id="debug" cols="80" rows="20"></textarea>
</body>
</html>

So, at line 20, at the second callback (back from the setTimeout), the parameter "jsonPostsResults" is always returned as null... I have no idea why. If I copy paste that 2nd request in a browser, it returns 100 results. Anybody had a problem like that with the Ajax/JQuery functions when calling it with a setTimeout?


It's because you haven't specify '&callback=?' at second request

Fix: setTimeout("callTwitterSearchApi(\"http://search.twitter.com/search.json" + jsonPostsResults.next_page + "&callback=?\")", 5000);

0

精彩评论

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

关注公众号