在jquery中打印数组的单个字段

Print single field of an array in jquery

本文关键字:单个 字段 数组 打印 jquery      更新时间:2023-09-26

我正在组织代码以执行自动完成并在mysql表中搜索用户。

查询可以工作,但我对ajax代码有问题。这是代码:

$(function()
{
    $("#search").keyup(function() 
    { 
        var inputSearch = $(this).val();
        var dataString = 'searchword='+ inputSearch;
        if(inputSearch !== '')
        {
            $.ajax(
            {
                type: "POST",
                url: "http://localhost/laravel/public/index.php/search",
                data: dataString,
                cache: false,
                success: function(data) 
                {
                    $.each(data, function(i, el) {
                        $("#divResult").html(console.log(el.nome)).show();
                    });
                }
            });
        }
        return false;    
    });
});

我想问一个比我更有经验的人,我如何才能从该数组中只打印用户名字段。

$("#divResult").html(console.log(el.nome)).show();——这里发生了什么?

你想要更像的东西

success: function(data) 
{
    var resultHtml = '';
    $.each(data, function(i, el) {
        resultHtml += el.nome +'<br />';
        // or, do away with resultHtml, just use:
        // $('#divResult').append(el.nome);
    });
    $("#divResult").html(resultHtml).show();
}

我发现resultHtml方法更可读。

您只需要在数据上循环:

success: function(data) {
    $.each(data, function(i, el) {
        console.log(el.nome);
    });
}

小提琴示例