代碼如下:
$(document).ready(function () { var res; $.ajax({ type: 'post', url: 'GridDemo.aspx/PlaceOrder', contentType: "application/json; charset=utf-8", dataType: 'json', success: function (results) { var strJSON = results.d; //得到的JSON var obj = eval("(" + strJSON + ")"); //轉換后的JSON對象 res = obj.a; console.log(obj.a); }, error: function () { alert('error'); } }); $("#attr01").wijgrid({ allowSorting: true, data: res, }); });
我理想的是先ajax得到數據,再綁定到控件,可事實是先執行的綁定,后執行ajax方法,js不是按順序執行嗎?
默認情況下JQuery的AJAX是異步執行的,所以它在去獲取數據的同時也在執行下面的綁定,因為獲取數據是需要一定的時間,所以你看到的效果是先綁定后獲取數據。只要添加添加async:false.即修改為同步了,具體的代碼如下:
$.ajax({ type: 'post', async: false, url: 'GridDemo.aspx/PlaceOrder', contentType: "application/json; charset=utf-8", dataType: 'json',