質問

I'm tryig to get my head around using jsonp due to cross domain restriction.

After searching through lot of forum entries in here and other sites..I have arrived at point where I do not know why one of the example is working but another example is not.The output of the both rest url are in same JSON format.

Twitter Feed Working Example: http://jsfiddle.net/fwXD2/1/

Code is pasted below. If I remove the datatype:'jsonp' then I get "Access-Control-Allow-Origin" error which is expected.

<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $.ajax({
                url: 'https://twitter.com/status/user_timeline/stephenfry?count=10&format=json',
                dataType: 'jsonp',
                success: function(dataWeGotViaJsonp){
                    var text = '';
                    var len = dataWeGotViaJsonp.length;
                    for(var i=0;i<len;i++){
                        twitterEntry = dataWeGotViaJsonp[i];
                        text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                    }
                    $('#twitterFeed').html(text);
                },
                error: function(e){  
                    $('#twitterFeed').html("No 'Access-Control-Allow-Origin' header is present on the requested resource.");
                } 
            });
        })
    </script>
</head>
<body>
    <div id = 'twitterFeed'></div>
</body>

Non Working Example: http://jsfiddle.net/kA6z5/

Thanks in advance for any help you can provide.

役に立ちましたか?

解決

In JSONP technique, server should wrap the response in javascript function. There is a clear explantion given on jsonp technique here:

jQuery's "dataType: 'jsonp'" will just make sure to add callback parameter to your url.

Just add a '&callback=func123' to both the URLs, twitter will respond you with wrapped data where as the other service is not.

twitter : URL

findschoolzones : URL

Its is server's responsibility to identify the callback parameter and returns a wrapped data.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top