AJAX JSON调用失败

时间:2017-03-21 18:40:52

标签: javascript json ajax

我正在进行AJAX调用,从特定网站提取JSON数据但由于某种原因我在接听电话之前收到错误。

错误讯息:

  

未捕获的TypeError:无法读取属性' addEventListener' null的   的script.js:2

代码:

var ajaxtest = document.getElementById("dmeo");

ajaxtest.addEventListener("click",function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET","https://learnwebcode.github.io/json-example/animals-1.json")//post if you want to send data
ourRequest.onload = function(){
   // console.log(ourRequest.responseText);//test logging to console.
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData[0]);
};
ourRequest.send();
});

2 个答案:

答案 0 :(得分:0)

解决了!好吧,我最终做的只是将它放入onclick事件并且它可以工作。

function Makecall(){
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET","https://learnwebcode.github.io/json-example/animals-1.json")//post if you want to send data
ourRequest.onload = function(){
   // console.log(ourRequest.responseText);//test logging to console.
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData[0]);
};
ourRequest.send();
};

答案 1 :(得分:-1)

错字? var ajaxtest = document.getElementById(" dmeo"); 应该"演示"