简体   繁体   English

无法从 post 函数编辑全局变量

[英]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.我正在向托管我的 HTML 文件的网络服务器发送一个 post 命令,我正在使用 jquery 这样做。

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.当我尝试使用 alert() 读取全局变量时,它说 0 但在 returnData 函数中,它给了我服务器返回的内容。

<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. HTTP Request 是异步操作,所以会在所有同步代码之后处理。 Read more about JavaScript Event Loop.阅读有关 JavaScript 事件循环的更多信息。 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.但一般情况下,JavaScript 会将变量值设置为 0,然后使用 postList() 发出 HTTP 请求,该请求只会在包含 alert() 的其余同步代码之后调用 returnData(),因此在调用 alert() 时) 变量的值为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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