【问题标题】:undefined value when edit using ajax使用 ajax 编辑时未定义的值
【发布时间】: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


【解决方案1】:

您的问题是回调中的 this 关键字是指窗口对象,而不是您期望的 .data 元素。

您可以执行以下操作。

我将元素存储在外部范围内以记住被点击的元素,因此我们可以在回调中访问其数据集。

$('.data').on('click', function(event){

        // here im storing the element
        //  you can probalby also access it with $(this) and store it
        const dataEl = event.target

        axios.post('ajax/edit_groups/' + dataEl.dataset.id)
        .then(function (response){

            // in the callback I access the element that is in the outer scope
            console.log("in: ", dataEl.dataset.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)
    })
}

注意:我没有测试代码,只是为了说明问题的解决方法。

您可能想寻找替代方法。在使用this 时,您实际上可以使用bind 和其他一些方法。

由于锚标记内有一个元素,因此需要确保不捕获它的点击事件。这与所谓的事件委托有关。

实现这一点的一种简单方法实际上是使用 CSS。

 .data span { pointer-events: none; }

还有其他选择。

【讨论】:

  • 我试过了,但仍然未定义,“Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, ...}" :"..
  • 嗯。你现在在记录什么?我很确定这种方法是您所需要的。您只需将元素存储在某处
  • yess.. 我记录了这个.. 我尝试记录 dataEl 但结果是 span 标签.. 我尝试将数据类和 data-id 放在 span 标签中,结果它的工作,id显示..但它一直在循环并且响应未定义..
  • 是的,那是因为您实际单击的是跨度而不是锚点。当涉及到这些细节时,这有点棘手。我更新了我的答案,向您展示了一种处理此类事情的方法。使用 CSS。
  • 我认为 response.data 是数据组。也可以试试response.data[0]
【解决方案2】:

试试这个从 data-id 属性中获取 id

console.log("in: ", $(this).dataset.id)

供参考 https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

【讨论】:

  • 他的方法应该也行。您所做的是通过反射属性获取器访问属性。不过,如果这有效,那么 get 属性也必须有效。它们是可以互换的。
  • 结果仍然未定义..“无法读取未定义的属性'id'”
  • 可能是选择返回数组的类。尝试在循环时分配唯一 id 并获取点击项的 id 并将其传递给
【解决方案3】:

由于 ajax 是异步的,所以不能直接调用响应。尝试在您的函数上添加异步等待,例如:

    $('.data').on('click', async function() {
    await 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);
        });
    });

【讨论】:

  • 您将 async await 与 promise 语法混合在一起。他的语法是有效的,你的可能不是。
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多