2014-01-10 126 views
-1

我正在測試是否可以將.json文件中的項目讀入javascript JSON對象並顯示內容。我需要存儲的變量R1陣列中的出價,並顯示它將.json文件讀入javascript JSON對象

代碼如下

<head> 
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> 
<script type="application/javascript"> 
function loadJSON() 
{ 
    var data_file = "data1.json"; 
    var http_request = new XMLHttpRequest(); 
    try{ 
     // Opera 8.0+, Firefox, Chrome, Safari 
     http_request = new XMLHttpRequest(); 
    }catch (e){ 
     // Internet Explorer Browsers 
     try{ 
     http_request = new ActiveXObject("Msxml2.XMLHTTP"); 
     }catch (e) { 
     try{ 
      http_request = new ActiveXObject("Microsoft.XMLHTTP"); 
     }catch (e){ 
      // Something went wrong 
      alert("Your browser broke!"); 
      return false; 
     } 
     } 
    } 
    http_request.onreadystatechange = function(){ 
     if (http_request.readyState == 4 ) 
     { 
     // Javascript function JSON.parse to parse JSON data 
     var jsonObj = JSON.parse(http_request.responseText); 


     var R1 = new Array();  

for(var i= 0 ; i< jsonObj.length; i++){ 
    R1.push(jsonObj[i].BID); 
    document.write(R1); 
} 



     } 
    } 
    http_request.open("GET", data_file, true); 
    http_request.send(); 
} 




</script> 

</body> 
</html> 

和我的data1.json如下

[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ] 
+1

爲什麼當你不使用它時,用jQuery標記問題? – Johan

+0

你想要什麼 –

+0

[解析與jQuery和Javascript的本地JSON文件]可能的重複(http://stackoverflow.com/questions/17944344/parse-local-json-file-with-jquery-and-javascript) – Johan

回答

0

是我們可以加載Json對象,正如我在我的一個JSP項目中所做的那樣。這裏是代碼,以便您可以輕鬆理解。它調用一個從DB準備JSON文件的servlet。

 

     $('document').ready(function(){ 
      $.ajax({ 
       type: 'POST', 
       url: 'getCities', 
       success: function(data) { 
        var response = JSON.parse(data); 
        var products = response['city']; 
        var product_html = ''; 
        $(products).each(function(index, value){ 
         product_html += ""+value['name']+""; 
        }); 
        product_html += ""; 
        $("#citylist").html(product_html); 
       } 
      }); 
     }); 

這裏「getCities」是從數據從數據庫中提取準備JSON文件的servlet。它實際上是填充與特定縣有關的下拉列表。

還有一件事我相信json文件是不正確的。請用一些json驗證器檢查格式。