【问题标题】:Removing an object from database and the DOM via AJAX通过 AJAX 从数据库和 DOM 中删除对象
【发布时间】:2020-11-09 21:15:00
【问题描述】:

所以我有这个简单的 AJAX 发布请求,它按照我的意愿从模型中删除对象,但我正在努力从 DOM 中正确删除它。

function removeFriend(id){

    let dataId = `${id}`

    $.ajax({
        type: 'POST',
        url: `/delete/friend`,
        data: {
            friend_id: `${id}`,
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
            action: 'post'
        },
        success: function(json){
            let tbody = document.querySelector('tbody');
            let row = tbody.querySelector('tr[data-id=dataId]');
            console.log(row);
            row.remove();
            alert('friend has been deleted')
        },
        error: function(xhr, errmsg, err) {
            console.log(error)
        }
    })
}

我不断收到index.js:119 Uncaught TypeError: Cannot read property 'remove' of null 并且console.log(row) 显示为空。我试过let row = tbody.querySelector('tr[data-id=`${id}`]');,结果一样。

我尝试过let row = tbody.querySelectorAll('tr[data-id=dataId]');,但console.log(row) 的输出是一个空的NodeList NodeList [],后跟index.js:119 Uncaught TypeError: row.remove is not a function

这是我的桌子的样子:

    <table class="table table-striped table-sm" id="my_friends">
        <thead>
            <tr>
                <th>Nick name</th>
                <th>First name</th>
                <th>Last name</th>
                <th>Likes</th>
                <th>DOB</th>
                <th>lives in</th>
                <th>Remove friend</th>
            </tr>
        </thead>
        <tbody>
        {% for friend in friends %}
        <tr data-id="{{ friend.id }}">
            <td>{{friend.nick_name}}</td>
            <td>{{friend.first_name}}</td>
            <td>{{friend.last_name}}</td>
            <td>{{friend.likes}}</td>
            <td>{{friend.dob | date:"Y-m-d"}}</td>
            <td>{{friend.lives_in}}</td>
            <td><button type="button" class="remove-friend" name="remove-friend" value="{{ friend.id }}">Remove</button></td>
        </tr>
        {% endfor %}
        </tbody>
    </table>

我知道我已经正确分配了 data 属性,因为我可以看到它显示在我的 Chrome 浏览器元素中。

【问题讨论】:

  • 你试过row.nodeValue = ''吗?
  • 试试这个tbody.querySelector('[data-id="' + dataId + '"]');

标签: javascript django ajax dom-manipulation


【解决方案1】:

在选择器中使用传递给删除好友函数的id

let row = tbody.querySelector(`tr[data-id="${id}"]`);

【讨论】:

  • 这是结果:Uncaught DOMException: Failed to execute 'querySelector' on 'Element': 'tr[data-id=15]' is not a valid selector.
  • 尝试在 id 周围加上双引号
  • 数字属性似乎需要引号
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 2023-01-30
相关资源
最近更新 更多