use*_*170 1 javascript jquery scope
我没有大量的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"
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?我认为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');
}
Run Code Online (Sandbox Code Playgroud)