访问 ajax 中的 javascript 变量成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30734372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access javascript variable inside ajax success
提问by Gibbs
var flag = false; //True if checkbox is checked
$.ajax(
... //type,url,beforeSend, I cannot able to access flag here
success: function()
{
//I cannot able to access flag here
}
);
Inside ajax, if i try to access flag
it says it is not defined. How do i use it inside ajax function?
在 ajax 中,如果我尝试访问flag
它,则表示它未定义。我如何在ajax函数中使用它?
Any Idea?
任何的想法?
Both flag and ajax is body of a function. Nothing else is present inside that function.
flag 和 ajax 都是函数体。该函数中不存在任何其他内容。
回答by aemonge
You got acces to the variable if you make it by reference. All objects in Javascript are references values, just the primitive values aren't ( such as; int, string, bool, etc ... )
如果您通过引用创建它,您就可以访问该变量。Javascript 中的所有对象都是引用值,只是原始值不是(例如;int、string、bool 等...)
So you can either declare your flag as an object:
所以你可以将你的标志声明为一个对象:
var flag = {}; //use object to endure references.
$.ajax(
... //type,url,beforeSend, I cannot able to access flag here
success: function()
{
console.log(flag) //you should have access
}
)
Or force the success function to have the parameters you want:
或者强制成功函数有你想要的参数:
var flag = true; //True if checkbox is checked
$.ajax(
... //type,url,beforeSend, I cannot 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`
)
回答by Aabid
Here is one way. The beforeSend callback option gives you access to both the jqXHR object and the ajax settings object.
这是一种方法。beforeSend 回调选项使您可以访问 jqXHR 对象和 ajax 设置对象。
You won't be able to use caturl in the append of error, as it will not be in synch with the request throwing error.
您将无法在错误追加中使用 caturl,因为它不会与抛出错误的请求同步。
$.ajax({
/* url, data ...& other opts*/
beforeSend:function( jqXHR, settings){
/* add url property and get value from settings (or from caturl)*/
jqXHR.url= settings.url;
},
/* error to be deprecated in jQuery 1.8 , superseded by "fail" */
error: function(jqXHR, , textStatus, error){
var url=jqXHR.url;
/* replace caturl with url in your append */
$('#showdata').prepend("ERROR : '" + error + "' trying to access: " + url + "</br>");
}