2012-02-22 7 views
-2

가능한 중복은 : Javascript를 사용하여 Json 문자열이 포함 된 텍스트 파일을 읽는 방법은 무엇입니까?


How to use a JSON file in javascript

나는 텍스트 파일에 JSON 문자열을 넣어. 이제 Javascript를 사용하여 문자열을 객체로 전송하기 위해이 파일을 읽고 싶습니다.

어떻게 파일을 읽을 수 있습니까?

+5

파일은 어디에 있습니까? 웹 페이지의 어떤 환경입니까? –

+1

[찾았습니다 (http://stackoverflow.com/search?q=javascript+read+json+file)? – Quentin

+0

javascript는이 매우 복잡한 PHP를이 작업을 훨씬 더 쉽게 만듭니다. –

답변

-1

JavaScript를 파일로로드하려면 XMLHttpRequest, 일명 AJAX 호출을 사용하십시오.

+1

OP는 파일이 서버에 있다고 말한 적이 없습니다. – jAndy

+2

사실, 그렇지만 가능성이있는 경우입니다. 작은 정보를 기반으로 추측 할만큼 충분히 확실합니다. 어쨌든 OP는 서버에 없다고 말한 적이 없습니다. –

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 그렇지 않으면 때문에 파이어 폭스와 크롬에서 작동 할 수 있습니다 파일이 서버에있는 경우 HTTP 요청.합니다

관련 문제