当我将项目拖到购物车区域时,我需要用信息填充我的数组,即使我放置了这个函数,我也需要在拖动中播种
var ProductInfo=new Array();
myGlobalArray=GetProductById(iProductId);
调用这个Ajax函数
function GetProductById(iProductId)
{
var ProductInfo=new Array();
console.log("2");
$.ajax({
type: 'POST',
url: 'services/ManageCategoriesServices.asmx/GetProductById',
dataType: 'xml',
'data': {'iProductId': iProductId },
success: function(data) {
source = null;
try
{
console.log("source product-> ",data.activeElement.childNodes);
myGlobalArray=TestProduct(data.activeElement.childNodes);
console.log("In Ajax myGlobalArray-> ",myGlobalArray); return myGlobalArray;
}
catch(e) {
$('#m_lblStatus').text('failed to read json');
}
},
fail: function() { $('#m_lblStatus').text('fail');}
});
return myGlobalArray;
}
我检查了我的 myGlobalArray 是否获得了我需要的完整信息,但是当我尝试复制数组时返回到我的第一个函数时
myGlobalArray=GetProductById(iProductId);
它是空的,上面写着
There are no child objects
我使用了全局数组,因为通常的方法行不通,所以我认为全局数组会起作用 但在 ajax 中没有,我看到它已满,但在第一个函数中它是空的。
In Ajax myGlobalArray-> ["medium_101-01-004-02.jpg", "303", "101-01-004-02", "44.95"]
After Ajax myGlobalArray-->[] There are no child objects
问题出在哪里?
最佳答案
AJAX 的意思是“异步 Javascript 和 XML”。 异步是这种情况下的关键词。问题是:返回在您的请求完成之前运行。解决方案:您可以在 onSuccess 事件处理程序中使用 myGlobalArray 变量,或者使用带有 async == false 选项的 ajax,如下所示:
$.ajax({
...,
async: false,
...,
});
关于javascript - ajax传递数组的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17134415/