我对JavaScript和Web编程一般非常陌生,需要一些帮助。我有一个需要通过JavaScript发送HTTP请求的需求,并需要将输出存储在变量中。我尝试仅使用调用URL:
https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015
但是它返回了一个认证错误,因为我没有发送我的API密钥,并且它没有在URL中显示如何发送API密钥。 API密钥被列为标头而不是参数,我不确定该怎么做。 我尝试使用XMLHttpRequest()类,但我不太确定它的确切作用,也无法使其工作。实际的HTTP请求
GET https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015 HTTP/1.1
Host: api.fantasydata.net
Ocp-Apim-Subscription-Key: ••••••••••••••••••••••••••••••••
我只需要弄清楚如何在javascript中将请求与密钥一起发送,以及如何将返回的JSON文档存储为变量。
编辑:到目前为止,我有以下内容:
function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
httpGet("https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015",key );
alert(xmlHttp.responseText);
var x = 0;
}
function httpGet(theUrl,key)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send( null );
return xmlHttp.responseText;
}
谢谢!