2012-02-22 54 views
-2

可能重複:
How to use a JSON file in javascript如何閱讀包含使用JavaScript的Json字符串的文本文件?

我把一個JSON字符串在文本文件中。 現在我想讀取這個文件,以便將字符串轉移到使用Javascript的對象。

如何讀取文件?

+5

該文件在哪裏?你有什麼樣的環境 - 一個網頁? – 2012-02-22 15:45:04

+1

你有[搜索](http://stackoverflow.com/search?q=javascript+read+json+file)? – Quentin 2012-02-22 15:45:55

+0

JavaScript使得這個非常複雜的PHP會更容易做到這一點... – 2012-02-22 16:35:33

回答

-1

使用XMLHttpRequest(又名AJAX調用)將文件加載到JavaScript中。

+1

OP從來沒有說過該文件位於服務器上。 – jAndy 2012-02-22 15:46:08

+2

確實如此,但它是一個可能的案例 - 當然還有足夠的猜測基礎上的小信息。畢竟,OP從來沒有說過*不在服務器上。 – 2012-02-22 15:47:53

0

好的,如果你想在客戶端上做到這一點,你可以使用HTML5文件API。這裏有一些示例代碼,這應該讓你開始。

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
      <html xmlns="http://www.w3.org/1999/xhtml"> 
      <head> 
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
      <title>Untitled Document</title> 
      <style type="text/css"> 
       body 
       { 
        font-size:18pt; 
       } 
      </style> 
      <script type="text/javascript"> 
       function init() { 
        var bHaveFileAPI = (window.File && window.FileReader); 

        if (!bHaveFileAPI) { 
         alert("This browser doesn't support the File API"); 
         return; 
        } 

        document.getElementById("fileElem").addEventListener("change", onFileChanged); 
       } 

       function onFileChanged(theEvt) { 
        var thefile = theEvt.target.files[0]; 

        // check to see if it is text 
        if (thefile.type != "text/plain") { 
         document.getElementById('filecontents').innerHTML = "No text file chosen"; 
         return;// this will just get out of the function. 
        } 

        var reader = new FileReader(); 
        //file reader has an event there is no need to assign an event listener the 
        //onload event can just be assign like the below. 
        reader.onload = function (evt) { 
         var resultText = evt.target.result; 
         document.getElementById('filecontents').innerHTML = resultText; 
        } 
      // readAsText is a native method of the FileReader object. 
        reader.readAsText(thefile); 
       } 

       window.addEventListener("load", init); 
      </script> 
      </head> 
      <body> 
      <h1>Reading File Data as Text</h1> 
      <form action=""> 
      <label>Select a file: </label> 
      <input type="file" name="files" id="fileElem" /> 
      </form> 
      <p>File contents: </p> 
      <textarea cols="80" rows="10" id="filecontents"></textarea> 
      </body> 
      </html> 

,因爲他們是唯一一次支持文件API,否則,這隻會​​在Firefox和Chrome工作,你可以,如果該文件是在服務器上的HTTP請求。

相關問題