How do I read contents from a server side file using javascript?
5 Answers
Ask the web server for it with Ajax. In jQuery speak, for instance:
jQuery.get('path/to/file/on/server.txt', null, function(data, status) {
// your file contents are in 'data'
});
1 Comment
WillyCornbread
Should be noted that the file must reside in the same domain as the request, otherwise a server side proxy will be necessary.
using Ajax (XmlHttpRequest) e.g. using jQuery:
Comments
You have to serve the file via a HTTP request (i.e., the file is available as a URL like www.conphloso.com/somefile.txt), which you can grab via an ajax request in the background.
Comments
This is not possible using plain javascript. Javascript runs in the client browser and you cannot access a file in server. You can use AJAX to do this.
8 Comments
AnthonyWJones
Sure it, is assuming the Javascript is running on the server, which it probably isn't but the question doesn't make that clear as yet
Jeremy L
This can be done with plain javascript, no additional frameworks required: var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4) { document.myForm.time.value=xmlhttp.responseText; } } xmlhttp.open("GET","time.asp",true); xmlhttp.send(null);
AnthonyWJones
I don't think a downvote was warranted, the answer is likely to be correct.
rahul
But you have to code from server side to process the AJAX request. Thats why I made the comment that it is not possible using plain javascript. Also I mentioned about AJAX in my answer.
AnthonyWJones
@Nerdling: that would the AJAX then that phoenix was refering to right? It would have been better for you to place this code in an answer than to place that unformatted mess in the comments.
|