使用JQuery的JSON Get请求(跨域) [英] JSON Get request using JQuery (cross-domain)

查看:235
本文介绍了使用JQuery的JSON Get请求(跨域)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的JSON GET请求的,我不控制域的API。

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

我的code是简单的:

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);
            }
        });
});

不过,由于这是一个跨域请求,我得到这个错误在Chrome控制台:

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

XMLHtt prequest无法加载http://pubapi.cryptsy.com/api.php?method=marketdatav2。没有访问控制 - 允许 - 原产地标头的请求的资源present。原产地http://fiddle.jshell.net,因此不允许访问。

当我尝试添加参数数据类型:JSONP控制台与此错误返回:

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

未捕获的SyntaxError:意外的标记:

Uncaught SyntaxError: Unexpected token :

但是,当我检查浏览器的网络选项卡中我看到,标题下的状态code是200 OK,我可以清楚地看到,在响应选项卡中充分反应,但控制台仍呈现意外令牌: 错误和JQuery的JSON请求仍然失败。

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.

这里的JS小提琴链接: http://jsfiddle.net/6Qcq2/ 你可以看到同样的结果

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

我曾尝试在 http://www.hurl.it 运行的URL,它显示我状态正常和响应一样,所以我一定是做错了什么。

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.

我有pretty的多浪费一整天试图找出如何解决这个问题。

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

您的帮助是非常AP preciated。

Your help is very much appreciated.

推荐答案

从API的响应是JSON,不是JSONP,所以只是改变了数据类型并没有帮助。

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

您可以使用代理服务器发出请求并开启JSON到JSONP:

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);
        }
    });
});

演示: http://jsfiddle.net/6Qcq2/1/

这篇关于使用JQuery的JSON Get请求(跨域)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆