我在 JavaScript 方面经验不足,而且我在使用变量范围和 jquery 时遇到了麻烦。我有以下结构:
function pass_variables()
{
username = "efcjoe"
response = post_variables(username)
alert(response)
}
function post_variables(username)
{
$.post(
'/path/to/url/',
{
'username': username,
},
function(data)
{
valid = (data != 0) ? true : false
// OPTION 1: If I put return here...
return valid; // ... the alert box in pass_variables says "undefined"
},
"text"
);
// OPTION 2: If I put return here...
return valid; // ... The alert box does not pop up, and Safari debug gives
// me the error: "Can't find variable: valid"
}
我是不是漏掉了什么?我认为 valid
应该是一个全局变量,因此选项 2 应该可以正常工作。我真的不确定选项 1。
谁能给我一些建议,让我知道如何才能最好地完成这项工作?
非常感谢。
最佳答案
Ajax 调用是异步的,这意味着它们会被调用但会等待执行完成。基本上,您的警报在 ajax 请求完成之前触发,并运行回调函数来更改您的变量。
您能做的最好的事情实际上是传递一个函数,以便在 ajax 请求完成时运行。这也消除了对全局变量的需求,因为其他插件、脚本可以改变它们的状态并使您的脚本容易出现错误、缺陷等,因此不受欢迎
例如
function foobar(){
//call function to do post request and also pass a function to run
//when post has returned
runPostRequest( callbackFn );
}
function runPostRequest(callback){
$.post( '/foo', callback );
}
function callbackFn( data ){
console.log('post request complete');
}
关于javascript - Jquery $.post() 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1251910/