gpt4 book ai didi

javascript - 如何使用 $.ajax{} 使用 ajax 更新 html

转载 作者:行者123 更新时间:2023-11-28 21:26:51 24 4
gpt4 key购买 nike

我有 javascript,它从 javascript 调用 Controller 方法并返回 json 对象。返回 json 对象后,我想更新搜索字段下方的表格,该表格将显示 json 对象的结果。基本上,我试图列出所有对象,但想根据表单上的某些搜索过滤出结果。

以下是我用来获取 json 对象的示例代码:

$.ajax({
type: "GET",
dataType: "json",
url: "/students/search/" + this.value,
success: function(data){
// logic to update field
});
});

更新:

JSON 对象:

[{"student":{"student_type":"D", "student_name":"Blah Blah"}}]

我的 html 中有一个表格:

<table id="studentTable">
</table>

我想将student_type和student_name添加到表中

最佳答案

假设从 Controller 返回的数据是一个对象数组,我在之前的项目中做过类似的事情:

使用 jQuery 模板插件:

$.each(data, function(index, element) {
var t = $.template("<tr><td>${student_type}</td><td>${student_name}</td></tr>");

var tdata = {
student_type: element.student.student_type,
student_name: element.student.student_name
};

$("#studentTable").append(t, tdata);

});

所有这些都应该放在成功回调函数中。如果您可以提供在 View 中的位置的 html,以及从 Controller 返回的 JSON,我可以更新我的答案以更好地反射(reflect)您的场景。

关于javascript - 如何使用 $.ajax{} 使用 ajax 更新 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4812168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com