【问题标题】:How to convert data from JSONP to JSON如何将数据从 JSONP 转换为 JSON
【发布时间】:2017-05-08 13:49:14
【问题描述】:

我正在使用返回 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 :

【问题讨论】:

  • API 返回 JSON 但你需要使用 JSONP,所以你运气不好。您必须从您自己的服务器端代理中获取内容,或者说服控制该 API 的任何人开始支持 JSONP(或 CORS 标头)。
  • JSONP 基本上只是将远程<script> 插入到当前文档中。服务器必须支持。
  • 我正在使用 HTML、CSS、JS 和 smmry api 来做一个副业。如何将脚本正确插入到文档中?
  • 加上 JSONP 不能与 POST 一起使用,而且 JSONP 请求不需要 crossDomain。

标签: javascript jquery json ajax


【解决方案1】:

最简单的方法是在您的服务器上使用服务器端代理。您不会遇到此模型的 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'
  });
});

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 2014-04-11
    • 2019-08-20
    • 2016-08-29
    • 2013-08-19
    • 2012-12-25
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    相关资源
    最近更新 更多