Просто мой код выглядит следующим образом:JSON возвращаемого значения глобальных переменной
var thevariable = 0;
For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop
thevariable = e.result;
});
}
моя главная проблема, что значение переменного остается «0», в течение всего цикла For, в то время как я только хочу быть «0 "в первом цикле, тогда он принимает результат, возвращаемый PHP, чтобы использовать его для цикла.
здесь мой реальный код, если вам нужно посмотреть:
var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
console.log();
document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
document.getElementById("invoker").innerText = ""+e.invoice;
orderinvoice = e.invoice;
if(i+1 == table.rows.length){
document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
});
Цикл for не ждет, пока ваш ** асинхронный вызов Ajax получит ответ. Вы не можете использовать цикл здесь. См. Http://stackoverflow.com/q/23667086/218196. –
Проведите некоторое исследование того, что означает «асинхронный», и тогда у вас может возникнуть идея, почему ваш 'for' работает до завершения до того, как будет выполнен первый асинхронный ответ. – jfriend00