![](/img/trans.png)
[英]How do I make my PHP API return JSON to a Javascript HTTP POST/GET request?
[英]How do I get the JSON from an API request into my page's javascript?
我正在尝试使用web api在JavaScript中返回JSON文件。 使用Alchemy API,调用将是以下URL:
http://access.alchemyapi.com/calls/url/URLGetTextSentiment?url=http%3A%2F%2Fwww.macrumors.com%2F2013%2F11%2F05%2Fapple-releases-itunes-11-1-3-with-equalizer-and-performance-improvements%2F&apikey=[secret]&outputMode=json
这将对macrumors文章进行情绪分析。 但是,我不确定如何将JSON文件实际存入javascript。 有人知道吗?
您正在访问的URL似乎返回JSON,因此请使用ajax get
请求
使用jQuery.get() :
var Url = 'http://access.alchemyapi.com/calls/url/URLGetTextSentiment?url=http%3A%2F%2Fwww.macrumors.com%2F2013%2F11%2F05%2Fapple-releases-itunes-11-1-3-with-equalizer-and-performance-improvements%2F&apikey=[secret]&outputMode=json'
$.get(
Url,
function(data, status, xhr){
alert(data);
}
);
您不能对客户端上的其他域使用AJAX调用,因为浏览器出于安全原因阻止了这一点。 如果您必须进行跨域调用,则需要使用JSONP。 这是你的代码的一个工作示例(sans jQuery!)的pastebin: http : //pastebin.com/8vN8LqWW
因此虽然可以在客户端处理这一切,但不建议这样做。 如果它仅用于测试或个人项目,那么如果您真的将其推送到公共网络,您将向世界展示您的秘密API密钥。 在服务器端进行API调用要好得多,即使用Node.js,Python,Ruby等。 AlchemyAPI有几个SDK可以帮助您入门。
顺便说一下,为了披露,我为AlchemyAPI工作。
我看不到Steve共享的pastebin并在jQuery中写了以下内容(我知道没有提到jQuery,但我认为这可以很容易地适应JS而不需要jQuery):
$.ajax({
url: 'https://access.alchemyapi.com/calls/text/TextGetTextSentiment',
dataType: 'jsonp',
jsonp: 'jsonp',
type: "post",
data: { apikey: 'APIKEYHERE', text: streamText, outputMode: 'json' },
success: function(res){
if (res["status"] === "OK") {
//Do something good
}
else if (res["status"] === "ERROR") {
//Do something bad
}
},
error: function(jqxhr) {
//console.log(jqxhr);
}
});
希望这有助于人们寻找它:)! 我还在这里创建了一个要点: https : //gist.github.com/Wysie/32b2f7276e4bd6acb66a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.