首页 > 解决方案 > 在 laravel 中通过 ajax 显示多维数组

问题描述

该表格显示数据库中要编辑的条目的数据。其中一列是二维数组,我不知道如何传递数据。

尝试了正常的 AJAX 显示代码

通过 COntroller 来的数据是: res.credential 看起来像

[
    [
        "Facebook","x11111111",
        "q1111111","w11111111"
    ],
    [
        "Linkedin","x222222222",
        "q222222","w222222222222"
    ],
    [
        "Twitter","x333",
        "q3333333","w3333333"
    ]
]

AJAX 看起来像:

$('.password-edit-btn').on('click', function (){
    var client_sel = $(this).data('id');
if (client_sel) {
    $.ajax({
        type: "GET",
        url: "/get_password_data?id="+client_sel,
        success: function (res) {
            if (res) {
                console.log(res.credential);
                $("#edit-password-client").empty(); 
                $("#edit-password-client").append('<option>'+ res.client +'</option>'); 
                $('#edit-password-remarks').val(res.remarks);
            }

// The problematic area is below
            if (res.credential) {
                $.each(res.credential, function (key, value) {
                    console.log(value)
                    $(".add-hf-accounts").append()
                });
            }
        }
    });
}

});

只需使用“add-hf-accounts”类在 div 中显示数据。

标签: ajaxlaravel

解决方案


非常感谢各位的帮助。

问题在于解析。我不得不使用 JSON.parse,然后它运行良好。以下是最终的工作答案。

if (res.credential) {
                $.each(JSON.parse(res.credential), function (key, value) {
                    $(".add-hf-accounts").append('<div class="hidden_event"><div class="form-group col-sm-2"><label>Account</label><select class="form-control" name="account[]"><option value="'+ value[0] +'"> '+ value[0] +'</option></select></div><div class="form-group col-sm-3"><label>URL</label><input type="text" class="form-control" placeholder="Accoutn URL" name="url[]" value="'+ value[1] +'"></div><div class="form-group col-sm-3"><label>Username</label><input type="text" class="form-control" placeholder="User Name" name="user[]" value="'+ value[2] +'"></div><div class="form-group col-sm-3"><label>Password</label><input type="text" class="form-control" placeholder="Password" name="password[]" value="'+ value[3] +'"></div><div class="form-group col-sm-1 acc-btn"> <br><button class="btn btn-danger remove " type="button"><i class="glyphicon glyphicon-remove"></i></button></div></div>');
                });
            }

推荐阅读