javascript - 如何将数据从 JSONP 转换为 JSON

标签 javascript jquery json ajax

我正在使用返回 JSON 的 API。不幸的是,由于 CORS,我无法将数据类型设置为 JSON,而必须使用 API 不支持的 JSONP。

根据我的理解,我可以通过给它一个回调函数将 JSONP 转换为 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);
};

我遇到错误

Uncaught SyntaxError: Unexpected token :

最佳答案

最简单的方法是在服务器上使用服务器端代理。使用此模型不会遇到 CORS 问题。

一个简单的 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);
    }
}

调用 ASPX 页面如下;

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Passthrough-proxy.aspx.cs" Inherits="_Default" %>

还有远程 URL 的配置条目,如下所示:

<add key="PassthroughTargetURL" value="http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL"/>

假设您调用的 URL 是恒定的,您应该获得预期的结果,但是通过您的代理 - 该代理位于您的服务器本地,因此 JSON 将按预期工作。

你的代码将变成这样:

$(document).ready(function() {
  $.ajax({
    type:'POST',
    url:'http://your.server/proxy.aspx',
    dataType: 'json'
  });
});

关于javascript - 如何将数据从 JSONP 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291558/

相关文章:

使用 knockout.js 的 JavaScript TreeView

javascript - appendChild 在 IE 中无法正常工作

jQuery ui 选项卡坏了?

javascript - 我一直在尝试使用 Node js 访问 json 文件中的数据,但输出未定义

javascript - node.js 无法从 mongoexport 读取 json

javascript - 将事件监听器添加到动态创建的元素中

javascript - Html5桌面通知php/mysql

json - 解码 map[string]interface{} 时出现 mgo 错误

php - Ajax 和 JSON 响应问题

jquery - 重构 jquery 以传递 jquery-lint