我最近开始学习JavaScript,我的学习过程很顺利,直到我学习到JSON,当我开始尝试从一个URL中获取JSON时,我卡得很厉害,我试过了我在这里找到的大量方法,以及大量不同的URL,但似乎没有任何工作。好吧,切入正题,这就是我的情况。
如果有谁能对这件事有所启发,或者简单的提供一个简单的代码,对我来说,会有很大的帮助。
<p> test </p>
<script>
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log("1");
console.log(req.responseText.name);
}
};
req.open("POST", "http://api.jsonbin.io/b/5ec04a83a47fdd6af1645b86", true);
console.log("2");
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("secret-key", "MYKEY");
console.log("3");
</script>
你根本忘记了 send()
请求
<p> test </p>
<script>
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log("1");
console.log(req.responseText.name);
}
};
req.open("POST", "http://api.jsonbin.io/b/5ec04a83a47fdd6af1645b86", true);
console.log("2");
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("secret-key", "MYKEY");
req.send(); // <--------------------- Check this
console.log("3");
</script>
为了执行您的请求,您错过了 req.send()
你必须检查控制台和检查器中的网络选项卡,在那里你会看到你是否有其他问题。
请注意,在一些浏览器中,如Firefox,你可能会被阻止与 "阻止加载混合活动内容 "的消息。这是发生在你在HTTPS页面中,你使用HTTP网址(像你这样)执行脚本时。这是一个安全行为,以避免像MITM这样的攻击,由于发布潜在的安全内容(你的密钥或其他东西)。
是的,你只是忘记了send()
const req = new XMLHttpRequest()
req.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if(req.readyState === XMLHttpRequest.DONE) {
var status = req.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(req.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
req.open("POST", "http://api.jsonbin.io/b/5ec04a83a47fdd6af1645b86", true);
console.log("2");
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("secret-key", "MYKEY");
console.log("3");
req.send(); // try this