如何阅读包含使用JavaScript的Json字符串的文本文件?

问题描述:

可能重复:
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

使用XMLHttpRequest(又名AJAX调用)将文件加载到JavaScript中。

+1

OP从来没有说过该文件位于服务器上。 – jAndy 2012-02-22 15:46:08

+2

确实如此,但它是一个可能的案例 - 当然还有足够的猜测基础上的小信息。毕竟,OP从来没有说过*不在服务器上。 – 2012-02-22 15:47:53

好的,如果你想在客户端上做到这一点,你可以使用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请求。