使用 Javascript 从经典 ASP 中的文件中读取文本

Read text from file in classic ASP using Javascript

本文关键字:文件 读取 取文本 ASP Javascript 经典 使用      更新时间:2023-09-26

我正在使用经典的ASP,并且正在尝试将特定文本文件的内容打印到屏幕上。我知道如何通过ASP在VBScript中做到这一点,但是如何通过ASP在Javascript中做到这一点呢?

基本上只是将 VBS 转换为 JS,只要您对两者有基本的了解,这并不难。

VBScript示例

<%@ 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 示例

<%@ LANGUAGE="JSCRIPT" %>
<%    
var fso = Server.CreateObject("Scripting.FileSystemObject");
var txt = fso.OpenTextFile("C:''Pathto''textfile.txt");
var content = txt.ReadAll();
Response.Write(content);
%>

请注意,如果您使用的是 JS,则需要转义 Windows 文件路径中的反斜杠

如果你使用的是纯JavaScript,你可以做如下的事情。 只需记住替换get函数的第一个参数将实际文件路径包括文件扩展名(例如:myfilename.txt)。您还必须确保您尝试打开的文件来自同一域。这是它如何工作的示例的链接(http://bytewarestudios.com/launchjs/get)。我从我编写的 JavaScript 库中删除了 get 函数,这样你就不必加载整个库了。

.HTML:

  <div id="results"></div>

JavaScript(将此代码放在脚本标签中,紧接在结束正文标签之前):

   //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