如何从函数中访问局部变量?

时间:2015-05-16 11:32:39

标签: javascript

function readFile(){
    var xmlhttp;

    if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari browser support
    {
        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;
            //alert(xmlhttp.responseText);
            output = xmlhttp.responseText; //output of txt file
        }
    }
    var data  =  xmlhttp.open("GET","read.txt",true); //file read
    xmlhttp.send();
}

window.setInterval(function(){
    /// call your function here
    readFile();
    var i = output; 
}, 1000); // it gives the result of txt file on every one second

var myResult = readFile();
alert(myResult); // I want to access the readfile() function output in variable  but it gives nothing

此代码为我提供了txt文件的输出第二次间隔时间,我的txt文件值每秒更改一次,但我无法访问此函数的输出以使用程序中的其他位置或函数。

我希望readfile函数的访问输出不起作用吗?任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

<script>
  function readFile(callback)
  {
    var xmlhttp;
    if(window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari browser support
    {
      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;
        if(typeof callback === 'function')
        {
          callback(xmlhttp.responseText);
        }
      }
    };
    var data = xmlhttp.open("GET", "read.txt", true); //file read
    xmlhttp.send();
  }
  window.setInterval(function()
  {
    readFile(function(data)
    {
      console.log(data)
    });
  }, 1000); // it give the result of txt file on every one second
  readFile(function(data)
  {
    console.log(data)
  });
</script>