Basic example of using .ajax() with JSONP?

前端 未结 4 1914
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:54

Please could someone help me work out how to get started with JSONP?

Code:

$(\'document\').ready(function() {
    var pm_url = \'http://twitter.com/s         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-22 00:26

    In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.

    Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.

    This does not work any more - as an exercise, see if you can replace it with the Github API:

    $('document').ready(function() {
        var pm_url = 'http://twitter.com/status';
        pm_url += '/user_timeline/stephenfry.json';
        pm_url += '?count=10&callback=photos';
        $.ajax({
            url: pm_url,
            dataType: 'jsonp',
            jsonpCallback: 'photos',
            jsonp: 'callback',
        });
    });
    function photos (data) {
        alert(data);
        console.log(data);
    };
    

    although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing

    alert(JSON.stringify(data));
    

    You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.

    
    
        
            JQuery (cross-domain) JSONP Twitter example
            
            
        
        
            

    提交回复
    热议问题