javascript – 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返回的结果将其用于for循环.

这里是我的真实代码,如果你需要看看:

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;
          }
 });

最佳答案 在一个循环块中,在一个ajax完成之前将运行另一个并且这是javascript自然处理.对于您的情况,您可以在成功事件结束时调用函数.做这样的事情:

var i = 0;    
doSt();

function doSt() {
    var orderinvoice = 0;

        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;
            }
            i++;
            if (i < table.rows.length) doSt();
        });
    }
点赞