尝试从git存储库中提取json格式的数据

时间:2017-06-14 18:48:30

标签: javascript json ajax github https

我是初学者,正在尝试学习ajax并使用json个文件。我想使用JSON格式的数据。但我的请求结果是一个空文本。 更新:以下是我的代码:

var quoteContainer=document.getElementById("random-quote");
var btn=document.getElementById("btn");
btn.addEventListener("click",function(){
   var myRequest=new XMLHttpRequest();

   myRequest.open("GET","https://raw.githubusercontent.com/4skinSkywalker/Database-Quotes-JSON/master/quotes.json",true);
   myRequest.addEventListener('load', function () {
       var myData=JSON.parse(myRequest.responseText);
       console.log(myRequest.responseText);
       renderHTML(myData);  
   });
   myRequest.send();
});


function renderHTML(data){
    var LenJson=data.length;
    var Num=Math.random()*LenJson;
    console.log(Num);
    var QuoteString="<p id='quote-text'>"+data[i].quoteText+"</p>"
    var AuthorString="<p id='quote-author'>"+data[i].quoteAuthor+"</p>"
    quoteContainer.insertAdjacentHTML('beforeend',QuoteString);
    quoteContainer.insertAdjacentHTML('beforeend',AuthorString);
}

它仍然没有返回任何数据。为什么?

2 个答案:

答案 0 :(得分:1)

您忘记在运行myRequest.send()方法后加入open(),这应该在行上。

更多信息:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

答案 1 :(得分:1)

您需要send()并等待它load

var quoteContainer = document.getElementById("random-quote");
var btn = document.getElementById("btn");

btn.addEventListener("click", function() {
  var myRequest = new XMLHttpRequest();

  myRequest.open("GET", "https://raw.githubusercontent.com/4skinSkywalker/Database-Quotes-JSON/master/quotes.json", true);
  
  myRequest.addEventListener('load', function() {
    var myData = JSON.parse(myRequest.responseText);

    renderHTML(myData);
  });
  
  myRequest.send();
});

function renderHTML(data) {
  var LenJson = data.length;
  var Num = Math.floor(Math.random() * LenJson);
  
  var QuoteString = "<p id='quote-text'>" + data[Num].quoteText + "</p>";
  var AuthorString = "<p id='quote-author'>" + data[Num].quoteAuthor + "</p>";
  
  quoteContainer.insertAdjacentHTML('beforeend', QuoteString);
  quoteContainer.insertAdjacentHTML('beforeend', AuthorString);
}
<button id="btn" type="button">Generate Random Quote</button>
<div id="random-quote"></div>