2010-06-11 66 views
2

我试图从只包含jQuery的小白问题变量(范围是什么?)

<?php 
echo 'here is a string'; 
?> 

我通过包含一个HTML文件,这样一个命名返回PHP文件中检索数据

<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <script> 
    var x; 
    $.get("return.php", function(data){ 
    x = data; 
}) 
function showAlert() {alert(x);} 

    $(document).ready(function(){ 
    alert(x); 
}); 
    </script> 
</head> 
<body> 
    <input type = "button" value = "Click here" onClick="showAlert();"> 
</body> 

</html> 

当按钮被点击时,它会检索并显示代码,但在$(document).ready事物上,它会显示“undefined”而不是return.php中的数据。任何解决方案

谢谢。在$不用彷徨又回到了味精可能

var x; 
function showAlert() {alert(x);} 

$(document).ready(function(){ 
    $.get("return.php", function(data){ 
     x = data; 
     showAlert(); 
    }) 
}); 

应该做工精细

回答

4

的的document.ready运行。

var x; 

function showAlert() {alert(x);} 

    $(document).ready(function(){ 
    $.get("return.php", function(data){ 
    x = data; 
    alert(x); 
    }); 
}); 
+1

+1,我只是写同样的答案:) – 2010-06-11 03:19:35

2

阿贾克斯可能尚未加载之前尚未

2

这不是一个范围问题,它是一个事件顺序问题。 $.get是一个异步调用,所以当你的页面加载到浏览器中时它可能还没有完成(这是一个相当小的页面,所以我想它的加载速度很快)。