Cross domain AJAX called with JSONP returns plain JSON

微笑、不失礼 提交于 2019-12-11 13:08:49

问题


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

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

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

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

Uncaught SyntaxError: Unexpected token :

In other words it does not recognize the json format.

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


回答1:


Since you dont have access to the server where the API is hosted, you use can a web service utility like CURL to access the API. AJAX calls requires CORS (Cross Origin Resource Sharing) to be enabled on the server where the API is served.

You can call a web service on your local server page via AJAX from where the CURL call will be made and appropriate response returned.




回答2:


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.

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.

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

What is JSONP all about?



来源:https://stackoverflow.com/questions/28124651/cross-domain-ajax-called-with-jsonp-returns-plain-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!