我是 ajax 和 Jquery 新手。我已经编写了代码,通过我正在设计的表单中的 ajax 调用自动填充组合框。现在,我想根据组合框中所选的值自动填充同一表单的其余字段,为此我需要另一个 ajax 调用,该调用将只返回一个 student
对象。通过这个对象,我可以像这样设置表单的字段:
$('#student_name').val(student.name);
$('#student_roll_num').val(student.roll_num);等等
其中name、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);
}
});
});
关于javascript - 使用 Jquery 和 Ajax 根据组合框中选定的值自动填充表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18810361/