如何将返回的 JavaScript 数组项添加到特定文本框

How do I add returned JavaScript array items to specific textboxes

本文关键字:添加 文本 数组 返回 JavaScript      更新时间:2023-09-26

我使用以下代码使用 AJAX 调用了一个 URL,它以这种格式在数组中返回了 2 个项目 ["item1", "item2"]

function getbook()
{        
    $.ajax({
        type: "POST",
        url: "/Home/getBooked",
        data: { "bookNumber": mobile },
        success: function(succ) { // I need to add the items in succ to some text boxes as shown below
            $.each(succ, function (index, element) {
                    $('#tb1').val(element);
                    $('#tb2').val(element);
            });                           
        },
        error: function(err) { 
            alert("An error is thrown"); 
        }
    });
}

但问题是两个文本框中都只显示succ数组中的最后一项。当我使用警报功能显示succ的内容时,它显示了这两个项目。显然我错过了一些东西。如果有人能帮忙,我会很高兴。

问题是你在每次迭代中设置值。尝试如下。

success: function (succ) { 
    $('#tb1').val(succ[0]);
    $('#tb2').val(succ[1]);
}
if the IDs of textbox is kind of sequence then we can resolve like bellow:
        $.each(succ, function (index, element) {
            $('#tb'+ (index + 1)).val(element);
        });