Reputation: 45
Tried this code to read data from a local text file. But I don't know why this is not working. Could someone help me with this problem. I can see in most of the answers in stackoverflow, they say that this is working, but this is not working for me. do I have to install anything for this?
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sample.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Upvotes: 0
Views: 5741
Reputation: 7139
The problem is that XMLHttpRequest
will not read files from the local filesystem (otherwise malicious websites could read files on your desktop!). Here are some solutions:
127.0.0.1
. For a quick and dirty solution, you can use Python's SimpleHTTPServer
or the Node.js http-server
package. For production, use Nginx or Apache.Upvotes: 2
Reputation: 4063
You can only read local files on the server side without user interaction. If you want to read a client side file, you have to use an html interaction element like:
<input type="file" id="openselect" />
Otherwise, if your file is on the server side, you could use something like:
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata;}
Upvotes: 0