如果我理解正確,您希望稍後在您的代碼中重用ajax響應。 如果是這樣,您當前的代碼將無法工作,因爲默認情況下,JavaScript引擎不會等待ajax請求的響應。換句話說下面的代碼將不起作用:
<script type="text/javascript">
$(document).ready(function(){
var x;
var y;
$.ajax({
url: 'ajaxload.php',
dataType: "json",
success: function(data) {
x= data.posX;
y= data.posX;
alert (x+" "+y); // I can se data but I need outside ajax call
}
});
alert(x+" "+y); // You won't see anything, because this data isn't yet populated. The reason for this is, the "success" function is called when the ajax request has finished (it has received a response).
})
</script>
您需要等待ajax響應。要做到這一點與jQuery你需要稍微修改代碼:
<script type="text/javascript">
$(document).ready(function(){
var data = $.parseJSON($.ajax({
url: 'ajaxload.php',
dataType: "json",
async: false
}).responseText); // This will wait until you get a response from the ajax request.
// Now you can use data.posX, data.posY later in your code and it will work.
var x = data.posX;
var y = data.posY;
alert(x+" "+y);
alert(data.posX+" "+data.posY);
});
</script>
你的意思是'window.x'和'window.y'? – Touki
這應該真的有效,你有沒有試過在ajax功能之外發出警報,你也缺少'});'在最後一行,這可能是問題以及 – Linas
ahha對不起,我正確});失蹤。我已經有了x值,我將通過php從數據庫中獲取它。 – Micky