我试图使用Web API在JavaScript中返回一个JSON文件。 使用炼金术API,通话将以下网址:
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
这将运行在一个加拿大家园文章情感分析。 不过,我不确定如何真正得到JSON文件转换为JavaScript。 有谁知道怎么样?
您正在访问显示的网址返回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的!): http://pastebin.com/8vN8LqWW
因此,尽管有可能处理这一切在客户端,但不推荐。 如果它只是用于测试或个人项目,这很好,但如果你真的推了这一点,你会暴露你的秘密API密钥世界公共网站。 这是更好的做出如何使用Node.js,Python和Ruby或类似的在服务器端,即API调用。 AlchemyAPI有几个软件开发工具包 ,以帮助您开始。
BTW,信息披露,我为AlchemyAPI工作。
我看不出这是由史蒂夫·共享,并写了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