weixin_33688840 2017-01-03 07:23 采纳率: 0%
浏览 55

jQuery Ajax嵌套回调

I have nested callabcks but resulted output is not ordered correctly. My ajax results are in ascending orders of id but html generated is random. can someone help me out pls?

var formatedhtml = '';
$.ajax({
    type: "POST",
    url: BASE_URL + 'index.php/orders/read',
    dataType: 'json',
    success: function(data) {

        $.each(data, function(key, value) {

            console.log(value);
            getdetails(value['id'], function(output) {
                formatedhtml = formatedhtml +
                    '<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
                    ' <div class="row">' +
                    ' <div class="orderno">' + value['id'] + '</div>' +
                    '<div class="tableno">' + value['tableno'] + '</div>' +
                    '<div class="ordertype">' + value['type'] + '</div>' +
                    '<div class="timestamp">' + value['created'] + '</div>' +
                    ' </div>' +
                    '<hr>';
                $.each(JSON.parse(output['items']), function(k, val) {
                    formatedhtml = formatedhtml + '<div class="row">' +
                        '<div class="quantity">' + val[3] + '</div>' +
                        '<div class="item">' + '</div>' +
                        '</div>';

                });
                formatedhtml = formatedhtml +
                    '<div class="row">' +
                    '<div class="notes">' + value['id'] + '</div>' +
                    '</div>' +
                    '</div>';
                $("#orderlist").html(formatedhtml);
                console.log(output);
            });

        });

    }
});

edit:

Here is getdetails function. its an ajax request.

function getdetails(id, callback) {
    var result;
    $.ajax({
        type: "POST",
        url: BASE_URL + 'index.php/orders/readdetails',
        dataType: 'json',
        data: {
            id: id,
        },
        success: function(data) {
            callback(data[0]);
        }
    });
};
  • 写回答

2条回答 默认 最新

  • ℙℕℤℝ 2017-01-03 07:40
    关注

    Use async:false in your getDetails() ajax call.

    function getdetails(id, callback) {
    var result;
    $.ajax({
        type: "POST",
        url: BASE_URL + 'index.php/orders/readdetails',
        dataType: 'json',
        async: false,
        data: {
            id: id,
        },
        success: function (data) {
            callback(data[0]);
    
    
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 streamingtool
  • ¥15 MATLAB图像问题
  • ¥20 树莓派5做人脸情感识别与反馈系统
  • ¥15 selenium 控制 chrome-for-testing 在 Linux 环境下报错 SessionNotCreatedException
  • ¥15 使用pyodbc操作SQL数据库
  • ¥15 MATLAB实现下列
  • ¥30 mininet可视化打不开.mn文件
  • ¥50 C# 全屏打开Edge浏览器
  • ¥80 WEBPACK性能优化
  • ¥30 python拟合回归分析