簡體   English   中英

如何將數據從JSONP轉換為JSON

[英]How to convert data from JSONP to JSON

我正在使用返回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'
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM