Javascript combined with ajax reads the contents of the TXT file

  • 2020-03-30 04:29:43
  • OfStack

The code is very simple, here is not much nonsense, directly on the source code

The HTML code


 <!doctype html>
 <html>
  <head>
      <meta charset="utf-8"/>
      </head>
      <body>
          <button type="button"  onclick="show()"> The request data </button>
         <script src="ajax.js"></script>
         <script>
           function show(){
             Ajax('read.txt?datetime=new Date.getTime ',function(str){alert(str);},function(){alert(' failed ');})
           };
         </script>
      </body>
 </html>

Javascript code


  function Ajax(url,fnSucc,fnFaild)
             {
                  //1. Create an ajax object
                if(window.XMLHttpRequest)
                 {// code for IE7+, Firefox, Chrome, Opera, Safari
                      var oAjax=new XMLHttpRequest();
                 }
                else
                 {// code for IE6, IE5
                     var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
                 }
                 //2. Link server (open connection to server)
                 //Open (method, file name, asynchronous transfer)
                 oAjax.open('GET',url,true);
                 //3. Send
                 oAjax.send();
                 //Receive returns
                 oAjax.onreadystatechange=function()
                    {
                      if (oAjax.readyState==4)
                      {
                        if(oAjax.status==200)
                          {
                            fnSucc(oAjax.responseText); 
                          }
                       else
                          {
                           fnFaild(oAjax.status);
                          }
                      };
                 };
              }

The requested file is read.txt

Fill in the content casually


Related articles: