2014-01-21 25 views
0

我正在尋找一種方法來加載位於與html和js文件相同的文件夾中的JSON文件。無論文件託管在Web服務器上還是分發用於本地脫機使用,該方法都應該可以正常工作。如何加載位於相同路徑的JSON文件?

我試圖用XMLHttpRequest獲取文件,但脫機使用這似乎只適用於Firefox。

任何幫助,將不勝感激!

+0

如果你絕望,可以使用'jsonp'實現。 – shakib

回答

0

沒有可靠的,跨瀏覽器的方式來編寫可以從用戶的文件系統加載文件的網頁 - 即使頁面從那裏加載。

改爲在JavaScript腳本中嵌入JSON。

0

您有兩種選擇。

1)將JSON數據嵌入到js腳本中。

2)使用一個小的PHP文件,獲取文件的內容,並通過使用AJAX帶來的JS腳本。

0

加載文件:data.json位於與HTML文件相同的路徑,這可能會幫助ü...

路徑

| - index.html的

| - 數據.json(Json文件)

<html> 
<head> 

    <title>Loading a Json using Jquery</title> 

    <style> 
     body{ 
      text-align: center; 
      font-family: arial; 
     } 

     .button{ 
      margin:20px; 
      font-size:16px; 
      font-weight: bold; 
      padding:5px 10px; 
     } 
    </style> 


</head> 
<body> 
    <a href="data.json" target="_blank">Open JSON file</a><br /> 
    <input type="button" value="Get and parse JSON" class="button" /> 
    <br /> 
    <span id="results"></span> 

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 

    <script> 

     //When DOM loaded we attach click event to button 
     $(document).ready(function() { 

      //after button is clicked we download the data 
      $('.button').click(function(){ 

       //start ajax request 
       $.ajax({ 
        url: "data.json", 
        //force to handle it as text 
        dataType: "text", 
        success: function(data) { 

         //data downloaded so we call parseJSON function 
         //and pass downloaded data 
         var json = $.parseJSON(data); 
         //now json variable contains data in json format 
         //let's display a few items 
         $('#results').html('Plugin name: ' + json.name + '<br />Author: ' + json.author.name); 
        } 
       }); 
      }); 
     }); 
    </script> 

</body> 
</html> 
相關問題