Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - JSONP cross origin error 'No Access-Control-Allow-Origin header is present'

I am using Ajax to get data from twitter using their API. I am trying to use jsonp and from what i can see and understand I think I am doing everything right (obviously not though).

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">  </script>
<script>
    $(document).ready(function () {
        $.ajax( {
            type: 'GET',
            datatype: 'jsonp',
            data: {},
            crossDomain: 'true',
            url: "http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=?",
            error: function(textStatus, errorThrown) {
                alert("error");
            },
            success: function(msg) {
                console.log(msg);
            }
        });
    });
</script>

The above code generates an error in both Chrome and Firefox XMLHttpRequest cannot load http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

From my understanding i thought that having the &callback=? and having the type set to jsonp would allow this to succeed. What's more is that I can see the JSON object being returned in fiddler it is just not being dealt with by the script. I have tried multiple API's with the same issue occurring.

One such API also works when entered into the address bar.

So I after extensive searching and looking do i need to some how set the origin to *? I thought this was more a server side issue?

I have also tried ?callback? but to no avail.

Any ideas would be awesome thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The said resource supports jsonp, so there is no need for CORS... the problem is datatype: 'jsonp' it should be dataType: 'jsonp'

$(document).ready(function () {
    $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        data: {},
        url: "http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=?",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR)
        },
        success: function (msg) {
            console.log(msg);
        }
    });
});

Demo: Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...