2010-06-11 24 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是一個異步調用,所以當你的頁面加載到瀏覽器中時它可能還沒有完成(這是一個相當小的頁面,所以我想它的加載速度很快)。