Jquery~$when_done_then的用法

对于$.ajax请求来说,如果层级比较多,程序看起来会比较乱,而为了解决这种问题,才有了$when...done...fail...then的封装,它将$.ajax这嵌套结构转成了顺序平行的结果,向下面的$.ajax写法,看起来很乱

    $.ajax({
        url: "/home/GetProduct",
        dataType: "JSON",
        type: "GET",
        success: function (data) {
            $.ajax({
                url: "/home/GetProduct",
                dataType: "JSON",
                type: "GET",
                success: function (data) {
                    $.ajax({
                        url: "/home/GetProduct",
                        dataType: "JSON",
                        type: "GET",
                        success: function (data) {
        
                        }
                }
        }

而它实现的功能无非就是外层执行完成后,去执行内层的代码代码,看下面的$.when写法,就清晰多了

    $.when($.ajax({
        url: "/home/GetProduct",
        dataType: "JSON",
        type: "GET",
        success: function (data) {
            alert(JSON.stringify(data));
        }
    })).done(function (data) {
        alert(data[0].Name);
    }).done(function (data) {
        alert(data[1].Name);
    }).fail(function () {
        alert("程序出现错误!");
    }).then(function (data) {
        alert("程序执行完成");
    });

而对于这种ajax的封装,在比较流行的node.js里也需要被看到,这就类似于方法的回调技术

在使用MVVM的KO上,更加得心应手,感觉$.when就是为了Knockoutjs而产生的!

    //MVVM数据绑定
    var MyModel = new model();
    $.when($.ajax({
        url: "/home/GetProduct",
        dataType: "JSON",
        type: "GET",
        success: function (data) {
            MyModel.PeopleList = ko.observableArray(data);//先为对象赋值
        }
    })).done(function (data) {
        ko.applyBindings(MyModel);//再绑定对象
    });

 

以后我们在进行前端开发时,应该多使用这种顺序的,平行的代码段,而少用嵌套的代码段,这只是大叔个人的见解。

posted @ 2016-05-20 13:50  张占岭  阅读(9317)  评论(0编辑  收藏  举报