Reputation: 87
I'm using classic ASP, and am trying to print the contents of a specific text file to the screen. I know how to do this in VBScript through ASP, but how can one do this in Javascript through ASP?
Upvotes: 1
Views: 2063
Reputation: 4638
It's basically just a case of translating your VBS into JS, it's not that difficult as long as you have a basic understanding of both.
VBScript example
<%@ LANGUAGE="VBSCRIPT" %>
<%
dim fso, txt, content
set fso = Server.CreateObject("Scripting.FilesystemObject")
set txt = fso.OpenTextFile("C:\Pathto\textfile.txt")
content = txt.ReadAll
Response.Write content
%>
JScript example
<%@ LANGUAGE="JSCRIPT" %>
<%
var fso = Server.CreateObject("Scripting.FileSystemObject");
var txt = fso.OpenTextFile("C:\\Pathto\\textfile.txt");
var content = txt.ReadAll();
Response.Write(content);
%>
Note that you need to escape the backslashes in Windows filepaths if you're using JS
Upvotes: 1
Reputation: 2191
If you are using plain JavaScript you can do something like the following. Just remember to replace the first parameter of the get function will the actual file path including the file extension name(example: myfilename.txt). You must also make sure that the file you are trying to open is from the same domain. Here is a link to an example of how it works (http://bytewarestudios.com/launchjs/get). I removed the get function from a JavaScript library I wrote so you wouldn't have to load the whole library.
HTML:
<div id="results"></div>
JavaScript(Place this code in a script tag right before the closing body tag):
//call the get function
get(pathToTextFile,function(data){
//display the file contents to the screen.
document.getElementById("results").innerHTML = data;
});
function get(url,fn){//begin ajax function
var contentType;
//variable to hold the xmlhttp object
var xmlhttp = null;
//if a contentType is not passed in
if(typeof arguments[1] === "function"){//begin if then else
//set it to default of text/html
contentType = "text/html";
}//end if then
else{
//set the contentType to the argument passed in
contentType = arguments[1];
}//end if then else
//if the browser contains the object
if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
//create a new XMLHttpRequest object
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
//create a new ActiveXObject
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}//end if then else
//add the event listenter
xmlhttp.onreadystatechange = function(){
//if the status of the request is good
if (xmlhttp.readyState===4 && xmlhttp.status===200){//begin if then
//get the response text and store it in the data variable
var data = xmlhttp.responseText;
//call the ajaxDone callback function
ajaxDone(data,fn);
}//end if then
};//end function
function ajaxDone(data,fn){//begin function
//call the anonymous function passing the data returned from the xmlhttp request
fn(data);
}//end function
Upvotes: 1