【发布时间】:2017-08-13 08:20:21
【问题描述】:
注意:我会详细说明我为这个问题找到的解决方法,但我仍然不明白为什么第一种方法对我不起作用/不起作用。
我的 HTML 文件有一个 jQuery 脚本,它应该通过 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 在我删除重置行时发送。
-
@MilanChheda
callback在我定义的地方被调用。我只放了定义,所以很清楚callback做了什么。一个单独的函数首先在那里被调用,callback在函数执行时得到它的返回结果。是的,$.post不在else内。我想了解的是为什么这会影响$.post发送的number的值。看到number是一个全局变量,我的期望是number的更新值将被发送而不是初始/重置值0。
标签: javascript php jquery ajax post