【问题标题】:JavaScript scoping rules possibly being tampered with by jQuery/Ajax?JavaScript 范围规则可能被 jQuery/Ajax 篡改?
【发布时间】: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


【解决方案1】:

正如您在此示例中所见,您对范围部分的看法是正确的,因此肯定还有其他问题,可能在回调中。也许您正试图以异步方式获取号码,在收到回复之前发布数据?

var condition = false;
var number = 0; //ensure that the variable has global scope

$("#button").click(function() {
  number = 0; // reset the value of the number every time the button is clicked
  function callback(returnedNumber) {
    if (condition == true) {
      //alert("Condition passes");
    } else {
      // assign returnedNumber to 'number', then initiate ajax POST request to server
      number = 23; // just assume returnedNumber is 23
    }
    condition = !condition;
    $("#result").text(`Result: ${number}. Setting condition to ${condition}`);
  }
  // Call the callback as an actual callback
  setTimeout(callback, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click...</button>
<div id="result"></div>

【讨论】:

  • 一定是这样。我用来获取新号码的函数确实是异步的——谷歌地图 API 距离矩阵服务。这是我第一次看到(现在理解)同步和异步调用之间的实际区别,所以我非常感谢你帮助阐明了这一点。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多