日期:2014-05-16  浏览次数:20793 次

js_ajax中变量的作用域
ajax的小程序 
 <body>
    <input type="button" onclick="showMsg()" value="调用ajax显示内容" >
    <span id="msg"></span>
  </body>
  <script type="text/javascript">
   var xmlHttp;
function showMsg(){
initXmlHttp();
xmlHttp.open("post","content.html");
xmlHttp.onreadystatechange =callBack;
xmlHttp.send(null);
}
function initXmlHttp(){
if(window.xmlHttpRequest){
xmlHttp=new xmlHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.xmlHttp");
}
}
function callBack(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("msg").innerHTML=xmlHttp.responseText;
}
}
  </script>
</html>
这样可以执行,但是代码一换
function showMsg(){
   var xmlHttp;
把xmlHttp的生成放到方法里面,就没有效果,怎么回事?
感觉逻辑从上往下执行,作用域没有问题,但是就是没有效果。
求教


------解决方案--------------------
function callBack(){
  if (xmlHttp.readyState==4 && xmlHttp.status==200){
    document.getElementById("msg").innerHTML=xmlHttp.responseText;
  }
}
这个 xmlHttp 如果不是全局变量就不能正常工作

如果要将 xmlHttp 做成局部变量,就要将回调函数也写成局部的

xmlHttp.onreadystatechange =callBack;
改写为
xmlHttp.onreadystatechange = function(){
  if (xmlHttp.readyState==4 && xmlHttp.status==200){
    document.getElementById("msg").innerHTML=xmlHttp.responseText;
  }
}