[英]Global variables in jQuery plugin
I am creating a jquery plugin. 我正在创建一个jQuery插件。 In that am using some global variablse $.rmtableparams.recordsCount: 0
is one of them. 在这种情况下,使用一些全局变量$.rmtableparams.recordsCount: 0
是其中之一。
I am assigned some values to this from one function inside an ajax call
. 我从inside an ajax call
一个函数为此分配了一些值。
callAjax = function (surl, pselector, pi, rec) {
$.ajax({
..
success: function (data) {
$.rmtableparams.recordsCount =10;
}
});
}
But while I am trying to access $.rmtableparams.recordsCount
in some other function it returns 0. But strange thing is that if i alert anything
before that it will returns 10
correctly. 但是,当我尝试在其他函数中访问$.rmtableparams.recordsCount
,它返回0。但是奇怪的是,如果在此之前i alert anything
发出i alert anything
, it will returns 10
正确it will returns 10
。
Ie: if my script is 即:如果我的脚本是
alert("hi");
alert($.rmtableparams.recordsCount);
the second alert will shows 10 第二个警报将显示10
But if only alert($.rmtableparams.recordsCount);
但是如果仅是alert($.rmtableparams.recordsCount);
is there it returns 0 它在那里返回0
I was wondered with this. 我对此感到惊讶。 If any body knows the reason please help me. 如果有人知道原因,请帮助我。
The assignment $.rmtableparams.recordsCount =10;
赋值$.rmtableparams.recordsCount =10;
is inside the success
callback of an $.ajax
request. 在$.ajax
请求的success
回调中。 So the value isn't assigned until the ajax call is completed, and a response received. 因此,直到ajax调用完成并收到响应后,才分配该值。 This happens fairly quickly, so while you're first alert
is waiting to be closed, the ajax response is received, and the assignment is processed. 这发生得相当快,因此当您第一次遇到alert
要关闭时,会收到ajax响应并处理分配。 Then, the second alert shows the new value. 然后,第二个警报显示新值。
If you leave out the first alert, the call is still being processed and the $.rmtableparams.recordsCount
value hasn't changed yet. 如果您没有发出第一个警报,则该呼叫仍在处理中,并且$.rmtableparams.recordsCount
值尚未更改。
It's as simple as that: AJAX stands for Asynchronous JavaScript And XML. 就这么简单:AJAX代表异步JavaScript和XML。 Async is key, but often overlooked... 异步是关键,但经常被忽略...
You can't just go ahead and set $.rmtableparams.recordsCount
because $.rmtableparams
doesn't exist. 您不能只是继续设置$.rmtableparams.recordsCount
因为$.rmtableparams
不存在。
You first need to set $.rmtableparams
: 您首先需要设置$.rmtableparams
:
$.rmtableparams = {};
Then you go ahead and add data to the object: 然后,继续向对象添加数据:
$.rmtableparams.recordsCount = 10;
Make sure that the success callback is being fired. 确保成功回调被触发。 Add an alert
or console.log
inside the callback to do the check. 在回调中添加alert
或console.log
进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.