gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:41:18 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com