javascript - 为什么 Javascript 代码无法运行?

标签 javascript json

我是 JavaScript 新手。这是我第一次真正尝试做一些除了运行 hello world 之外的事情。我正在尝试从网址检索信息并显示它。我检查了 url,它返回 json。 “Hello World”代码运行,但一旦我添加检索脚本标记内的 json 的代码,什么也不会发生。我没有收到任何语法错误。

<!DOCTYPE HTML>

<html>

<body>

  <p>Header...</p>

  <script>
    document.write("Hello World");

    var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "json";
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();

};

  getJSON("http://api.tvmaze.com/schedule?country=US&date=2016-08-31",
  function(err, data) {
  if (err != null) {
    alert("Something went wrong: " + err);
  } else {
    alert("Your query count: " + data.query.count);
  }
});

  </script>
  <p>...Footer</p>

</body>

</html>

最佳答案

我检查了你的 html 和 js,快速查看控制台后发现问题出在这一行

alert("Your query count: " + data.query.count);

将“data.query.count”更改为“data.length”

alert("Your query count: " + data.length);

调试代码是查找错误的最简单方法之一。 您基本上可以在任何浏览器中按 F12 来检查幕后的内容

enter image description here

关于javascript - 为什么 Javascript 代码无法运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296023/

相关文章:

javascript - 如何延迟 document.ready 直到设置变量?

Javascript d3 : Is there a way to programmatically stop dragging an item?

javascript - 从对象中获取子 JSON 值

json - 使用Elephantbird读取JSON时出错-PIG

javascript - 在三个 JS 上创建从经纬度开始的路径

javascript - 如何避免在 Angular 4 上多次调用相同的 API?

javascript - java中将hashmaps转换为json的hashmap。当发送到jsp时,我用javascript解析它。但在 javascript 中解析不正确

javascript - Three.js 和 Angular4 以及 JSONLoader

java - 根据属性值过滤 Jackson 的 JsonNode 元素

javascript - 如何在 Javascript 中正确地对数组进行 URL 编码?