Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - JSON Get request using JQuery (cross-domain)

I'm trying to make a simple JSON get request to an API on a domain that I do not control.

My code is simply:

$(document).ready(function () {
        $.ajax({
            type: 'GET',
            url: 'http://pubapi.cryptsy.com/api.php?method=marketdatav2',
            success: function (data) {
                console.log(data);
            }
        });
});

But since that is a cross-domain request, I am getting this error in the Chrome Console:

XMLHttpRequest cannot load http://pubapi.cryptsy.com/api.php?method=marketdatav2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

And when I try to add the parameter dataType: 'jsonp' the Console returns with this error:

Uncaught SyntaxError: Unexpected token :

But when I examine the Network tab in Chrome I see that under Headers the Status Code is 200 OK and I can actually see the full response in the Response tab, but the console is still showing the "Unexpected Token :" error and the JQuery JSON request is still failing.

Here's the JS Fiddle link: http://jsfiddle.net/6Qcq2/ You can see the same results

I have tried running the url on http://www.hurl.it and it shows me Status OK and the response as well, so I must be doing something wrong.

I've pretty much wasted the whole day trying to figure out how to get around this problem.

Your help is very much appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The response from the API is JSON, not JSONP, so just changing the data type doesn't help.

You can use a proxy that makes the request and turns the JSON into JSONP:

$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: 'http://jsonp.guffa.com/Proxy.ashx?url=pubapi.cryptsy.com%2fapi.php%3fmethod=marketdatav2',
        dataType: 'jsonp',
        success: function (data) {
            console.log(data);
        }
    });
});

Demo: http://jsfiddle.net/6Qcq2/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...