[英]global variable in javascript used in a ajax call
I declared a global variable var idCategories= new Array();
我声明了一个全局变量
var idCategories= new Array();
in my file.js
I use it in this function 在我的
file.js
我在此功能中使用它
function test() {
$.ajax({
type: "GET",
url: "http://my_site/api/categories?ws_key="
+ ws_key
+ "&PHP_AUTH_USER=" + PHP_AUTH_USER,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
var i = 0;
$(xml).find("category").each(function () {
idCategories[i] = $(this).attr('id');
// length increments at each iteration
alert("length=" + idCategories.length);
i = i + 1;
});
}
alert("length=" + idCategories.length); //returns 0
}
in the function parseXml(xml)
the array length is well incremented but outside of this function length = 0! 在函数
parseXml(xml)
,数组长度增加得很好,但是在此函数长度之外= 0! so that I can't use the array idCategories
in another function! 这样我就不能在另一个函数中使用数组
idCategories
!
The problem is that the AJAX call is ASYNC. 问题在于AJAX调用是ASYNC。 So
parseXml
will most likely, if not always, be called after your alert is called. 因此,很有可能(如果并非总是)在调用警报后调用
parseXml
。
Why not: 为什么不:
function test() {
$.ajax({
type: "GET",
url: "http://my_site/api/categories?ws_key="
+ ws_key
+ "&PHP_AUTH_USER=" + PHP_AUTH_USER,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
var i = 0;
$(xml).find("category").each(function () {
idCategories[i] = $(this).attr('id');
// length increments at each iteration
alert("length=" + idCategories.length);
i = i + 1;
});
alert("length=" + idCategories.length); //returns 0
}
}
try to using object and array 尝试使用对象和数组
function parseXml(xml) {var obj={};var a = [];
$(xml).find("category").each(function(i) {
obj["idCategory"]= $(this).attr('id');
a.push(obj);
alert("length="+a.length);// length increments at each iteration
});
}
alert("length="+a.length);//returns 0
}
$.ajay is by default asynchronus function! $ .ajay默认是异步功能! That means thet when it starts to execute it does not block application flow.
这意味着,当它开始执行时,它不会阻止应用程序流。 you're alert statement executes before $.ajax success function.
您的警报语句在$ .ajax成功函数之前执行。 You have two solutions.
您有两种解决方案。
set asny parameter to false. 将asny参数设置为false。
$.ajax({ type: "GET", async: false,
... ...
call alert in parseXml function. parseXml函数中的呼叫警报。
I belive you're best bet is async:false , but correct way of doing it would be to advance script execution after $.ajax call is finished (execute next step in parsexml function). 我相信你最好的选择是async:false ,但是正确的方法是在$ .ajax调用完成后执行脚本执行(在parsexml函数中执行下一步)。
This question appears multiple times a day. 这个问题一天出现多次。 You are making an asynchronous call, that alert line fires BEFORE the Ajax call is returned.
您正在进行异步调用,在返回Ajax调用之前,警报行将触发。
Ajax is asyncronous. Ajax是异步的。 Your
alert("length="+idCategories.length);
您的
alert("length="+idCategories.length);
code is called before response is delivered. 在传递响应之前调用代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.