注意:我將指定解決方案,我發現這個問題,但我仍然不明白爲什麼第一種方法沒有/不適合我。JavaScript範圍規則可能被jQuery/Ajax篡改?
我有一個jQuery腳本用於我的HTML文件,該文件應該通過ajax請求向服務器發送一個數字。這裏是我的腳本是佈局方式:
// Beginning of script
var number = 0; //ensure that the variable has global scope
// Send number to server on click of button (which has type 'button' not 'submit') in HTML document
$(document).ready(function() {
$("#button").click(function() {
number = 0; // reset the value of the number every time the button is clicked
// A function runs here and returns a number, and it has a callback (which gets passed that returned number).
// Callback is defined as follows:
function callback(returnedNumber) {
if (condition == true) {
alert("Condition passes");
} else {
// assign returnedNumber to 'number', then initiate ajax POST request to server
number = returnedNumber; // just assume returnedNumber is 23
}
// Notice that the ajax request is NOT initiated as part of the else statement.
$.post("test.php", { key: number }, function(data) {
$("#resultDiv").html(data);
});
}
});
});
現在這裏是服務器上的「test.php的」文件如下:
<?php
echo var_dump($_POST);
?>
當回調的條件未通過,var_dump()
顯示$_POST["key"]
的值仍然是0而不是23,這是我感到困惑的地方。我對JS範圍規則的理解是,一旦變量被全局聲明,只要var
關鍵字不用於在函數中重新聲明該變量,函數就可以修改其值。我認爲這意味着使用我的回調來重新分配number
的值也會改變全局變量number
的值,從而允許我將它發送到服務器,而不會將ajax請求作爲重新分配變量的else語句的一部分。那麼,我有什麼錯誤?如果有文件可以幫助澄清我的誤解,請提供鏈接。 :)
我的解決方法:我只是將ajax POST請求附加到else語句,並且按照我的意願工作。但我不明白爲什麼當請求不是else語句的一部分時,ajax請求沒有采用更新後的值number
。
謝謝!
你在哪裏調用'callback'功能?其次,'$ .post'不在'else'裏面,就像你在你的問題中提到的那樣。 –
您對範圍界定是正確的。如果您從不將數字重置爲0,會發送什麼內容? –
@MarcodeZeeuw 0在我刪除復位行時發送。 –