jQuery Ajax執行順序問題


代碼如下:

$(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不是按順序執行嗎?

默認情況下JQueryAJAX是異步執行的,所以它在去獲取數據的同時也在執行下面的綁定,因為獲取數據是需要一定的時間,所以你看到的效果是先綁定后獲取數據。只要添加添加async:false.即修改為同步了,具體的代碼如下:

 

$.ajax({
   type: 'post',
   async: false,
   url: 'GridDemo.aspx/PlaceOrder',
   contentType: "application/json; charset=utf-8",
   dataType: 'json',

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM