2016-09-14 22 views
-3

我遇到了一些問題與我的JavaScript。我試圖加載JSON陣列AG-電網這樣和下面的工作很好,因爲我只是從JSON文件加載JSON:從javascript獲取錯誤嘗試加載json

var httpRequest = new XMLHttpRequest(); 
    httpRequest.open('GET', '../dist/output.json'); 
    httpRequest.send(); 
    httpRequest.onreadystatechange = function() { 
     if (httpRequest.readyState == 4 && httpRequest.status == 200) { 
      var httpResult = JSON.parse(httpRequest.responseText); 


      function isNumeric(n) { 
       return !isNaN(parseFloat(n)) && isFinite(n); 
      } 

      var parsedData = httpResult.map(function(obj) { 
       return Object.keys(obj).reduce(function(memo, key) { 
        var value = obj[key]; 
        memo[key] = isNumeric(value) ? Number(value) : value; 

        return memo; 
       }, {}) 
      }) 

但是,當我做以下列方式(即從一個jsp獲取JSON數組,執行console.log(jSONArray),其中顯示正常,但我得到的錯誤:

var jsonArray = document.getElementById("jsonArray"); 
     console.log(jsonArray); 
     var httpRequest = new XMLHttpRequest(); 
     httpRequest.open('GET', jsonArray); 
     httpRequest.send(); 
     httpRequest.onreadystatechange = function() { 
      if (httpRequest.readyState == 4 && httpRequest.status == 200) { 
       var httpResult = JSON.parse(httpRequest.responseText); 


       function isNumeric(n) { 
        return !isNaN(parseFloat(n)) && isFinite(n); 
       } 

       var parsedData = httpResult.map(function(obj) { 
        return Object.keys(obj).reduce(function(memo, key) { 
         var value = obj[key]; 
         memo[key] = isNumeric(value) ? Number(value) : value; 

         return memo; 
        }, {}) 
       }) 

我得到以下錯誤:

Failed to load resource: the server responded with a status of 404 (Not Found) 

如何改變第一個代碼,以便我可以正確讀取json數組,其中包含所有json數據。

UPDATE:

jsonArray是從JSP以下:

JSONArray jsonArray = new JSONArray(orderDetailsList1); 

<input type="hidden" value="<%out.println(jsonArray);%>" id="jsonArray"/> 
+2

爲什麼?您的網址錯誤。怎麼修?找出正確的URL。 –

+1

什麼是#jsonArray元素? –

+0

@MarcB哪個網址? – Shek

回答

0

jsonArray是DOM對象。要訪問其屬性,請使用value屬性:

httpRequest.open('GET', jsonArray.value); 
+0

好吧,我明白了,我得到null值,我不知道不知道爲什麼jsonArray被從jsp傳遞給js文件。 – Shek

相關問題