首先曬下本身代碼ajax
for ( var i = 0; i < rows.length; i++) { $.ajax({ type:'POST', url:'${ctx }/admin/store_item/findStoreItemsByType?typeid=' +flag+'&id='+rows[i].id,//請求的url地址 async: false,//設置成同步 dataType:'json', success:function(data){ if(flag==1){ $('#chexingtable').datagrid('updateRow',{ index:i, row:{price:data.price1,sumprice:data.price1*data.bz_gs} }); }else if(flag==2){ $('#chexingtable').datagrid('updateRow',{ index:i, row:{price:data.price2,sumprice:data.price2*data.bz_gs} }); }else if(flag==3){ $('#chexingtable').datagrid('updateRow',{ index:i, row:{price:data.price3,sumprice:data.price3*data.bz_gs} }); }else if(flag==4){ $('#chexingtable').datagrid('updateRow',{ index:i, row:{price:data.price4,sumprice:data.price4*data.bz_gs} }); } } }); }
剛開始的時候,每次循環是獲取不到ajax中的值的,在ajax中,若是想獲取到變量I,那麼也是有問題了。json
解決了半小時,終於明白了問題的所在:多線程
for 循環是一個單線程的東西,而ajax是多線程的,之因此稱之爲異步同步,是由於執行到ajax的時候去後臺開啓了一個線程,可是for循環自己就是一個單線程的東西,那麼執行到ajax的時候,ajax開啓了一個線程,for異步
循環是沒有等他的,知道for循環結束的時候,纔會把ajax返回的數據拿回來,因此會出問題async
解決辦法:只須要把ajax改爲同步的就能夠了,每次for循環,都要去加載ajax方法,而且拿到他返回的數據,只須要在ajax中間加一個代碼就能夠搞定了。async: false,//設置成同步url