2017-08-13 31 views
-1

注意:我將指定解決方案,我發現這個問題,但我仍然不明白爲什麼第一種方法沒有/不適合我。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

謝謝!

+2

你在哪裏調用'callback'功能?其次,'$ .post'不在'else'裏面,就像你在你的問題中提到的那樣。 –

+0

您對範圍界定是正確的。如果您從不將數字重置爲0,會發送什麼內容? –

+0

@MarcodeZeeuw 0在我刪除復位行時發送。 –

回答

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>

+1

這就是它。我用來獲取新號碼的功能確實是異步的 - Google Maps API距離矩陣服務。這是我第一次看到(並且現在理解)同步和異步調用之間的實際區別,所以我非常感謝您幫助解決這個問題。謝謝! –