1

I am trying to read test.txt through javascript and jquery in the HTML page textread.html stored in the same directory. But I get the following error:

Method 1 jQuery Method


jQuery error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.


jQuery: `

$.getJSON('test.txt', function(data) {
    console.log(data);
});

`


Method 2 javascript Method


javascript error: Cross origin requests are only supported for HTTP.


javascript:

`

if (xmlhttp != null)    {
    xmlhttp.open("GET","test.txt",false); // the false makes this synchronous!
    xmlhttp.send();
    var text = xmlhttp.responseText;
}

`


I have also tried alternative code

I am not hosting this application as I will be deploying it using PhoneGap as mobile applications.

Please provide me with a solution to read file under these circumstances. As an alternative solution is HTML5 FileReader advisable?

2 Answers 2

1

If you are using HTML 5 i found a really nice tutorial:

Reading Files using HTML 5

Html:

<div id="page-wrapper">

   <h1>Text File Reader</h1>
   <div>
      Select a text file: 
      <input type="file" id="fileInput">
   </div>
   <pre id="fileDisplayArea"><pre>

</div>

JavaScript:

window.onload = function() {
   var fileInput = document.getElementById('fileInput');
   var fileDisplayArea = document.getElementById('fileDisplayArea');

   fileInput.addEventListener('change', function(e) {
      var file = fileInput.files[0];
      var textType = /text.*/;

      if (file.type.match(textType)) {
         var reader = new FileReader();

         reader.onload = function(e) {
            fileDisplayArea.innerText = reader.result;
         }

         reader.readAsText(file);   
      } else {
         fileDisplayArea.innerText = "File not supported!"
      }
   });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Using JQuery you could try using ajax:

$.ajax({
   url : 'test.txt',
   success : function (data) {
      console.log(data);
   }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.