根据组合框中的选定值自动填充表单,使用 Jquery 和 Ajax

Autopopulate form based on selected value from combo box with Jquery and Ajax

本文关键字:表单 填充 使用 Ajax Jquery 组合      更新时间:2023-09-26

我是ajax和Jquery的新手。我已经编写了代码,以我正在设计的形式中的 ajax 调用自动填充组合框。现在我想根据组合框中的选定值自动替换相同形式的其余字段,为此我需要另一个 ajax 调用,它将只返回一个student对象。有了这个对象,我可以像这样设置表单的字段:

$('#student_name').val(student.name); $('#student_roll_num').val(student.roll_num); etc.

其中,名称、roll_num是表单字段的 ID。

我以以下方式写:

//This following function will get called when one value from the combo box is 
//selected
 $("select#student_id").change(function(){
    var student_id = $(this).val(); //Here I am getting the selected value from 
    //the combo box
    $.ajax({
        url: "/students_database?student_id="+student_id, //this is the url that will
        //send me one student object
        dataType: "json",
        success: /*YET TO BE FILLED WITH CODE TO AUTO 
        /* POPULATE REST OF THE FIELDS*/ 
});

实际上,在这里我无法决定如何访问重新调整的学生对象,以便我可以像上面所说的那样访问其字段。所以,如果有人好心地帮助我做到这一点,我将不胜感激。另外,如果有更好的方法,请提出建议。谢谢。

假设你从 ajax 调用中获取了一个学生的 json,这应该可以工作:

 $("select#student_id").change(function(){
    var student_id = $(this).val(); //Here I am getting the selected value from 
    //the combo box
    $.ajax({
        url: "/students_database?student_id="+student_id, //this is the url that will
        //send me one student object
        dataType: "json",
        success: function(student) {
           $('#student_name').val(student.name);
           $('#student_roll_num').val(student.roll_num);
        }    
    });
 });