[英]How to convert data from JSONP to JSON
I'm using an API that returns a JSON. 我正在使用返回JSON的API。 Unfortunately because of CORS, I'm unable to set datatype as JSON and have to use JSONP, which the API doesn't support.
不幸的是,由于CORS,我无法将数据类型设置为JSON,并且必须使用API不支持的JSONP。
From my understanding, I can convert JSONP to JSON by giving it a callback function. 根据我的理解,我可以通过给它一个回调函数将JSONP转换为JSON。 It's not working and I couldn't find solutions online.
它不起作用,我无法在线找到解决方案。 Any help would be appreciated for me to convert the JSONP datatype to JSON.
我将很高兴将JSONP数据类型转换为JSON。
$(document).ready(function() {
$.ajax({
type:'POST',
url:'http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonpFunc',
jsonp:'callback'
});
});
function jsonpFunc(data){
console.log(data);
};
Error I'm getting 我得到的错误
Uncaught SyntaxError: Unexpected token :
The simplest way to do this is to use a server-side proxy on your server. 最简单的方法是在服务器上使用服务器端代理。 You do not run into CORS issues with this model.
您不会遇到此模型的CORS问题。
A simple example C# proxy might be: 一个简单的例子C#代理可能是:
using System;
using System.Web.UI;
using System.Net;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProcessRequest(this.Page);
}
public void ProcessRequest(Page context)
{
WebClient client = new WebClient();
string BaseUrl = ConfigurationManager.AppSettings["PassthroughTargetURL"];
string _url = BaseUrl;
context.Response.AddHeader("Content-type","application/json");
string _out = client.DownloadString(_url);
context.Response.Write(_out);
}
}
with a calling ASPX page as follows; 调用ASPX页面如下;
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Passthrough-proxy.aspx.cs" Inherits="_Default" %>
And a config entry for the remote URL, like so: 以及远程URL的配置条目,如下所示:
<add key="PassthroughTargetURL" value="http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL"/>
Assuming the URL you are calling is constant, you should get the expected result, but via your proxy - which is local to your server, so JSON will work as expected. 假设您调用的URL是常量,您应该获得预期的结果,但是通过您的代理 - 这是您服务器的本地代码,因此JSON将按预期工作。
Your code would then become something like: 您的代码将变为类似于:
$(document).ready(function() {
$.ajax({
type:'POST',
url:'http://your.server/proxy.aspx',
dataType: 'json'
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.