使用Javascript在web应用程序上自动填充输入框

Auto Fill input boxes on web app using Javascript

本文关键字:填充 输入 程序上 应用程序 Javascript web 应用 使用      更新时间:2023-09-26

我正在开发一个web应用程序,该应用程序应该使用ajax连接到数据库,并具有基本的CRUD功能。除了更新之外,一切都很好。在选择数据库条目时,我希望它使用javascript用现有数据预填充输入框。

    $(document).ready(function() {
    $.ajax({
        url : '/animal',
        method : 'GET'
    }).then(function(animals) {
        for (var i = 0; i < animals.length; i++) {
            var animal = animals[i];
            var row = '<option value="' + animal.animalId + '">'
                        + animal.commonName
                        + '</option>';
            $("#animals").append(row);  
        }
    });
    $.ajax({
        url : '/food',
        method : 'GET'
    }).then(function(foods) {
        for (var i = 0; i < foods.length; i++) {
            var food = foods[i];
            var row = '<option value="' + food.foodId + '">'
                        + food.foodName
                        + '</option>';
            $("#foods").append(row);
        }
    });
$("#animals").change(function() {
    $.ajax({
        url : '/animal/' + $("#animals").val(),
        method : 'GET'
    }).then(function(task) {
        console.log($("#animals").val());
        $("#cName").val(animals.commonName);
        $("#sName").val(animals.sciName);
        $("#food").val(animals.foodId);
        $("#infoLink").val(animals.infoLink);
        });
    });
$("#submit").click(function() {
    var animal = {};
    animals.commonName = $("#cName").val();
    animals.sciName = $("#sName").val();
    animals.foodId = $("#food").val();
    animals.infoLink = $("#infoLink").val();
    $.ajax({
        url : '/animal/' + animals.animalId,
        method : 'PUT',
        data : JSON.stringify(animal),
        contentType : 'application/JSON'
    }).then(function() {
        window.location.href = "/animal/index";
        });
    });
});

这就是我目前拥有的javascript,我不知道出了什么问题。任何帮助都将不胜感激。

我看到的几个问题:

var animal = {}; //You define "animal" here
animals.commonName = $("#cName").val(); //..but use "animals" here to populate the object
animals.sciName = $("#sName").val();
animals.foodId = $("#food").val();
animals.infoLink = $("#infoLink").val();

我建议:

var animal = {
    commonName: $("#cName").val(),
    sciName: $("#sName").val(),
    foodId: $("#food").val(),
    infoLink: $("#infoLink").val()
};

这里是

then(function(task) { //Your result is named "task"
    console.log($("#animals").val());
    $("#cName").val(animals.commonName); //..but you try to use "animals" which is going to be undefined
    $("#sName").val(animals.sciName);
    $("#food").val(animals.foodId);
    $("#infoLink").val(animals.infoLink);
    });
});

并修复将task更改为animals或将两个变量名更改为其他名称的问题。