繁体   English   中英

如何通过Django将JavaScript确认响应发送到脚本以根据响应执行操作?

[英]How do I send a JavaScript confirm response over Django to a script to perform operations based on the response?

我是Django的新手,目前正在尝试构建一个简单的To-Do应用程序。 我目前可以使用HTML表格在网页上显示我的待办事项列表,但是为了删除它,我在每个名为"Delete"条目的末尾添加了新行,并带有a href element, on click event将其发送到JS函数,该函数会弹出确认消息,询问用户是否确实要删除它。 我将响应存储在一个名为response的变量中。 现在,我的问题是如何在django中发送此响应以实际上能够删除该条目? 到目前为止,这是我所做的,并且没有任何效果。 所有帮助将不胜感激。 谢谢。

{% for item in task %}
    <tr>
    <td>{{ item.task_name }}</td>
    <td>{{ item.task_priority }}</td>
    <td>{{ item.task_status }}</td>
    <td>{{ item.target_date }}</td>
    <td><a href="" onclick="return delete_function()">Delete</a></td>
        <p id="delete"></p>
        </tr>
    {% endfor %}

    </table>
<script>
    function delete_function() {
        var response = confirm("Are you sure you want to delete this item?");
        if (response == true){
            response.post()
        }
    }
</script>

在我的视图页面中,我具有此函数来处理此post方法:

def view_task(request):
    if request.method == 'GET':
        context = dict()
        context['task'] = Task.objects.all()
        return render(request, 'todo/view_tasks.html', context)

    if request.method == 'POST':
        task_name = request.post['task_name']
        Task.objects.delete(task_name)
        Task.objects.save()

我究竟做错了什么? 另外,您还可以在何时何地使用post and get或至少将我引向有关同一主题的一些很好回答的问题吗?

我认为这不是解决问题的好方法,

尝试这样做:

在您的template.html中:

<form method="POST" action="">
    {% csrf_token %}
    <input type="submit" name="delete_amount" onclick="delete_me(event)" />
</form>

在您的view.py中:

#just in case you have other form
if 'delete_amount' in request.POST:
    # do your deleting query here
    print('deleting amount')

并在您的javascript.js中:

<script>
function delete_me(e)
{
     if(!confirm('Are you sure you want to delete this?')){
          //prevent sending the request when user clicked 'Cancel'
          e.preventDefault();
     }
}

</script>

希望这会有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM