简体   繁体   中英

Cannot edit global variables from post function

I am sending a post command to the webserver hosting my HTML file and I am using jquery to do so.

When I try to read the global variable with alert() it says 0 but in the returnData function, it gives me what the server returned.

<script src = "jquery.js"></script>
<script>

var faces = 0;

postList()

alert(window.faces) //gives me 0

//function with the post command
function postList(){
  $.post("/",{command : "2"},returnData);
}

function returnData(returnData,status){
  //try to save the data
  window.faces = returnData;
  alert(window.faces); //gives me the data from the server
}

</script>

HTTP Request is an asynchronous operation, so it will be processed after all synchronous code. Read more about JavaScript Event Loop. But in general, JavaScript will set the variable value to 0, then make an HTTP request with postList() which will call returnData() only after the rest of synchronous code, which contains alert(), so at the time of calling alert() value of the variable would be 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM