Reputation: 1707
i tried a lot for this, but didnt find the answer . How can i read a file using javascript or html . I have a text file "sample.txt" and i have some information in it . It is placed in the same folder as the html file is placed where the html file contains the html code that deals with this file . I just want to read the information from the file and display it on some div or whatever, i mainly want to know how to read a file .
Will provide more information if necessary .
Thanks
Upvotes: 4
Views: 1642
Reputation: 18253
You can do a regular Ajax request without jQuery aswell to read a file.
Following uses a GET request to get data from myfile.txt and outputs it to the DIV-tag with id output.
<script>
function ajaxGet()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","myfile.txt",true);
xmlhttp.send();
}
ajaxGet();
</script>
<div id="output"></div>
Upvotes: 1
Reputation: 1346
At first: JavaScript is executed on client-side. Though you have to put up an AJAX-Request to fetch the content of your file. I think jQuery's load()
seems to be the easiest way to achieve this.
For example:
$('#theContentElement').load('sample.txt');
Upvotes: 3