简体   繁体   English

我到底如何编写一个回调函数来更改jquery的AJAX中的全局变量?

[英]How exactly do I write a callback function to change a global variable inside AJAX for jquery?

Okay, so I look around a lot of answers and none of them seems helpful in what I want to achieve. 好的,所以我环顾了很多答案,但这些答案似乎都对我想要实现的目标没有帮助。 Say I have the following code: 说我有以下代码:

var n = 0;
$.ajax({
    ...
    success: function(data){
        n = Math.floor((Math.random()*10) + 1);
        somefunction(n);
    }
});

console.log(n) // n would obviously be 0 again

I had done it by making it synchronous using async:false , but from what I read, it's bad for the user experience as it freezes up the browser as it waits for result. 我通过使用async:false使其同步来完成此操作,但是从我的阅读中了解,这对用户体验不利,因为它在等待结果时冻结了浏览器。 how exactly do I implement the callback function in the above case to allow global variable n to be modified after ajax call? 在上述情况下,如何精确实现回调函数以允许在ajax调用后修改全局变量n

Async functions are executed in a different thread (non-blocking) thus the callback will be called past your next instruction: 异步函数在另一个线程(非阻塞)中执行,因此回调将在您的下一条指令之后被调用:

console.log(n);

n is set after the callback (success function) is called but the log is before the async function is done. n在调用回调(成功函数)之后设置,但日志在异步函数完成之前设置。 An easy solution is to wrap your code in a function and call it after jQuery calls success function. 一个简单的解决方案是将您的代码包装在一个函数中,并在jQuery调用成功函数之后调用它。 Note that you won't need to reference the global variable as it will be set outside of the jQuery scope and accessible to operation_x function scope. 请注意,您将不需要引用全局变量,因为它将在jQuery范围之外设置并且可以由operation_x函数范围访问。

var n = 0;
function operation_x(){
    console.log(n); // n is set to random value
}
$.ajax({
    ...
    success: function(data){
        n = Math.floor((Math.random()*10) + 1);
        somefunction(n);
        operation_x();
    }
});
console.log(n); // n is 0

You can use JavaScript local storage: 您可以使用JavaScript本地存储:

 $.ajax({
    ...
    success: function(data){
        n = Math.floor((Math.random()*10) + 1);
        somefunction(n);
localStorage.setItem("n", 100)
    }
});

var n;
if(typeof(Storage) !== "undefined") {
    // Code for localStorage.
    n = localStorage.getItem("lastname");
} else {
    // Sorry! No Web Storage support..
}

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

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