在div中添加响应ajax

时间:2019-02-10 19:46:55

标签: json ajax laravel append

我正在尝试将json格式的响应添加到列中,但出现以下错误:“未捕获的TypeError:response [i] .name.appendTo不是函数”。

function allUsers(){
        $(".error").remove();
        $("#tabla").remove();
        $.ajax({
            type: "GET",
            url: "mylocalhost/public/api/user",
            contentType: "application/json",    
            dataType:'json',

             beforeSend: function(request) {
                    request.setRequestHeader("Authorization", localStorage.getItem("token"));
                },
            success: function(response){
                console.log(response);




for (i = 0; i < response.length; i++) {

                    $('<div class="prueba"/><br>')+(response[i].name).appendTo('#filaNombre');

                    ...

2 个答案:

答案 0 :(得分:1)

尝试更改此行:

$('<div class="prueba"/><br>')+(response[i].name).appendTo('#filaNombre');

对此:

$('<div class="prueba"><br>' + response[i].name + '</div>').appendTo('#filaNombre');

答案 1 :(得分:1)

使用以下代码使用forEach附加名称

response.forEach((item)=> {
    $('#filaNombre').append(`<div class="prueba">${item.name}</div>`);
});

allUsers()用于填充JSON响应

function allUsers() {
    $(".error").remove();
    $("#tabla").remove();
    $.ajax({
        type: "GET",
        url: "mylocalhost/public/api/user",
        contentType: "application/json",    
        dataType:'json',

         beforeSend: function (request) {
                request.setRequestHeader("Authorization", localStorage.getItem("token"));
            },
        success: function (response) {
          if (response) {
            response.forEach((item)=> {
                $('#filaNombre').append(`<div class="prueba">${item.name}</div>`);
            });
          } else {
            $('#filaNombre').append(`<div class="prueba">No User Found</div>`);
          }
        }
    });
}