var flag = false; //True if checkbox is checked
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(){
// I'm not able to access flag here
}
});
ajax 内でアクセスしようとすると、flag
定義されていないと表示されます。ajax 関数内でこれを使用するにはどうすればよいですか?
何か案が?
flag と ajax は両方とも関数の本体です。その関数内には他に何も存在しません。
ベストアンサー1
参照によって変数を作成すると、その変数にアクセスできます。Javascript のすべてのオブジェクトは参照値ですが、プリミティブ値 (int、string、bool など) は参照値ではありません。
したがって、フラグをオブジェクトとして宣言することもできます。
var flag = {}; //use object to endure references.
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(){
console.log(flag) //you should have access
}
});
または、成功関数に必要なパラメータを強制的に設定することもできます。
var flag = true; //True if checkbox is checked
$.ajax({
... //type, url, beforeSend, I'm not able to access flag here
success: function(flag){
console.log(flag) //you should have access
}.bind(this, flag) // Bind set first the function scope, and then the parameters. So success function will set to it's parameter array, `flag`
});