【发布时间】:2020-08-13 03:44:14
【问题描述】:
我正在尝试使用 ajax 从我的数据库中获取数据。所以在控制器中我得到了 id,但是当去编辑模式时,id 是未定义的。
这里是控制器中的代码:
router.post('/ajax/edit_groups/:id', async (req, res) => {
console.log("edit")
let [data_group, err] = await model.getById(req.params.id)
console.log(req.params.id)
console.log(data_group)
res.json(data_group)
});
ejs 代码:
<table id="groups_table" class="table table-striped table-bordered" style="width: 100%;font-size:14px;">
<thead class="thead-dark">
<tr style="text-align: center;">
<th>Group Name</th>
<th>Group Description</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<% if(groupData){
for(var i=0;i < groupData.length; i++){
if(groupData[i].role == 1) groupData[i].role = "Admin";
else groupData[i].role = "User";
%>
<tr>
<td><%= groupData[i].name%></td>
<td><%= groupData[i].desc%></td>
<td><%= groupData[i].role%></td>
<td>
<div class="text-center">
<a href="#" class="data" title="Edit" data-id="<%= groupData[i].id%>">
<span class="fas fa-edit fa-lg"style="color: #000000; font-size: 15px;">
</a>
<a href="" title="Delete">
<span class="fas fa-trash-alt fa-lg"
style="color: rgb(206, 17, 17); font-size: 15px;">
</a>
</div>
</td>
</tr>
<% };%>
<% }%>
</tbody>
</table>
在这里我得到了 data-id 值。 编辑模态代码:
ejs 中的脚本:
$('.data').on('click', function(){
axios.post('ajax/edit_groups/' + $(this).attr("data-id"))
.then(function (response){
console.log("in: ", $(this).attr("data-id"))
$('#editGroups').modal('show');
$('#id_group').val(response.data_group[0].id);
$('#name').val(response.data_group[0].group_name);
$('#desc').val(response.data_group[0].group_desc);
$('#inputRole').val(response.data_group[0].role);
}).catch(function (error){
console.log(error)
})
})
在这里,控制台日志的结果,数据ID是未定义的..所以idk如何解决这个..我还是nodejs ejs的新手
【问题讨论】:
-
内部函数中的
this到底指的是什么?可以登录this吗? -
@TheFool im 使用 $(this) 选择 data-id 的属性..
-
是的,所以当您在内部函数中使用 console.log(this) 时。这是什么?
-
@TheFool 它显示“Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, ...}” ...
-
这就是你的问题。这是指窗口而不是 .data 元素。
标签: javascript html node.js express ejs