【发布时间】:2018-01-17 13:25:51
【问题描述】:
我是 JavaScript 新手。我正在尝试使用 XMLHttpRequest 从 Cisco Meraki 的 API 获取信息。我没有得到我希望得到的结果,这将是我们安装了 Meraki 设备的组织的列表。我在某处读到 XMLHttpRequests 不适用于跨域访问,所以如果我应该使用其他东西,请告诉我。也很可能我的代码中有一些我没有捕捉到的错误。
我查看了大量与 API 对话的示例,但没有一个,我发现这些示例涉及将唯一的 API 密钥从用户输入传递到表单的 get 语句中。我在函数底部添加了 console.log(),以确保我的变量从调用此函数的 html 表单中获取值,并且它们是。
以下是我在运行该函数后在浏览器中看到的错误:
XMLHttpRequest {onreadystatechange: ƒ, readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, ...} addAdmin.php:62 XHR 加载失败:选项“https://n159.meraki.com/api/v0/organizations”。 listOrgs @ addAdmin.php:62 onclick @ addAdmin.php:43 addAdmin.php:62 XHR 加载失败:选项“https://n159.meraki.com/api/v0/organizations”。
这是我的代码:
function listOrgs() {
var apikey = document.getElementById("apikeyinput").value;
var shard = document.getElementById("shardinput").value;
var xhttp, orgData, txt, x, dbParam, fullURL = "";
fullURL = "https://" + shard + ".meraki.com/api/v0/organizations";
xhttp = new XMLHttpRequest();
xhttp.open("GET", fullURL, true);
xhttp.setRequestHeader("Access-Control-Allow-Origin", "Content-Type");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, X-
Requested-With");
xhttp.setRequestHeader("X-Cisco-Meraki-API-Key", apikey);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
xhttp.onreadystatechange = function writeTable() {
if(this.readyState == 4 && this.status == 200) {
orgData = JSON.parse(this.responseText);
txt += "<table boarder='1'>";
for (x in orgData) {
txt += "<tr><td>" + orgData[x].name + "</td></tr>";
txt += "<tr><td>" + orgData[x].id + "</td></tr>";
};
txt += "</table>"
document.getElementById("printOrgs").innerHTML = txt;
};
}
console.log(fullURL);
console.log(apikey);
console.log(shard);
console.log(xhttp);
}
【问题讨论】: