使用JSONP调用的跨域AJAX返回纯JSON [英] Cross domain AJAX called with JSONP returns plain JSON

查看:134
本文介绍了使用JSONP调用的跨域AJAX返回纯JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用的API遇到问题.该API返回纯JSON,但它会跨域AJAX调用,因此我必须使用jsonp.

I have encountered a problem with an API I want to use. The API returns plain JSON but its a cross domain AJAX call so I have to use jsonp.

            $.ajax({
                type: "GET",
                url: url + query,
                contentType: "application/json",
                dataType: "jsonp",
                success: function(data){
                    console.log(data);
                }
            });

问题是当我将dataType更改为"json"时发生错误:

The problem is when I change the dataType to "json" an error occurs:

请求的请求上没有'Access-Control-Allow-Origin'标头 资源.因此,不允许访问原始"X".

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'X' is therefore not allowed access.

这是因为它是跨域Ajax调用.但是当它是jsonp时会说:

This is because its a cross domain ajax call. But when it is jsonp it says:

未捕获到的SyntaxError:意外令牌:

Uncaught SyntaxError: Unexpected token :

换句话说,它无法识别json格式.

In other words it does not recognize the json format.

我正在使用jquery进行ajax调用.有什么建议可以解决这个问题吗?

I am using jquery for the ajax call. Any suggestions how to solve this?

推荐答案

有几种绕过跨域限制的方法(CORS,JSONP,iframe传输等),但是所有方法都具有API服务器需要共同的特点公司的.因此,如果您没有在API服务器上的权限,就不会遇到跨域限制.

There are several methods of bypassing cross-domain restrictions (CORS, JSONP, Iframe transport, etc.) but all methods have in common that the API server needs to corporate. So if you don’t have privileges on the API server, you cannot come across the cross-domain restrictions.

完成此工作的唯一方法是在您可以控制的API前面放置一个代理(该代理可以位于同一域中,也可以注入适当的CORS标头).但是,这会影响性能,并可能产生法律影响.

The only way to make this work would be putting a proxy in front of the API that you can control (the proxy could either live on the same domain or inject the appropriate CORS headers). However, this will affect performance and might also have legal implications.

关于JSONP,这是一个很好的解释,说明其工作方式和原因:

Regarding JSONP, here’s an excellent explanation of how and why this works:

JSONP的全部含义是什么?

这篇关于使用JSONP调用的跨域AJAX返回纯JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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