作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用返回 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/
我是一名优秀的程序员,十分优秀!