无法使用JavaScript从URL获取JSON

3
我最近开始学习JavaScript,学习进程一直很顺利,但在学到JSON时遇到了困难。我试着从URL中获取JSON数据,但却遇到了严重的问题。我尝试了这里找到的许多方法和不同的URL,但都没有成功。废话不说,这是我的做法:
  • 我使用IIS创建本地服务器,并在那里运行我的脚本;
  • 我在JSONbin.io上创建了一个简单的JSON文件;
  • 我正在尝试使用我从JSONbin网站获取的代码来访问它;
  • 我为调试创建了一些console.logs;
  • 我发现控制台虽然没有指出任何错误,但请求函数从未运行;
  • MYKEY是我从JSONbin.io获取的秘密密钥。

如果有人能对此事提供帮助,或者提供一个适用于我的简单代码,那将非常有帮助。

<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>

3个回答

4

你只是忘记了要调用 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>


2
为了执行你的请求,你需要在末尾添加 req.send()。 你需要检查控制台和检查器中的网络选项卡,这样你才能看到是否有其他问题。
请注意,在某些浏览器(如Firefox)中,你可能会遇到“被阻止加载混合活动内容”的信息。当你在HTTPS页面上使用HTTP URL(就像你现在做的一样)来执行脚本时,这种情况会发生。这是一种安全操作,旨在防止攻击(例如MITM),因为可以发布潜在的安全内容(例如你的密钥或其他重要信息)。

1

是的,你只是忘记了发送(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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接