繁体   English   中英

姜戈; 使用 ajax 时重定向无法按预期工作

[英]Django; redirect doesn't work as expected when using ajax

我正在使用 ajax 创建删除功能。 重定向没有按预期工作。

js

function deleteEntry(entry) {

    var id = $entry.data('id')
    $.ajax({
        url:'/blog/delete/' + id,
        method: 'DELETE',
        beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRFToken', csrf_token)
            }
        })
    }
}

views.py

def delete_entry(request, pk):
    if request.method == 'DELETE':
        entry = get_object_or_404(Entry, id=pk)
        entry.delete()
        return HttpResponseRedirect(reverse_lazy('blog:list_entry'))

做功能的时候命令行是这样的

[13/Sep/2018 16:06:02] "DELETE /blog/delete/14 HTTP/1.1" 302 0
[13/Sep/2018 16:06:02] "DELETE /blog/list HTTP/1.1" 200 9878
[13/Sep/2018 16:06:02] "GET / HTTP/1.1" 200 10605

我想让页面重定向到blog/list但页面重定向到/ 我不想为此视图创建模板,而且我正在考虑执行诸如确认窗口之类的操作,因此我想使用 js 调用该函数。

我怎样才能解决这个问题?

$.ajax({
    url:'/blog/delete/' + id,
    method: 'DELETE',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRFToken', csrf_token)
    },
    success: function () {
       window.location.href = {% url 'the_get_url_you_wanted_to_redirect_to' %}
    }
})

请注意,这是一个在 stackoverflow 中多次提出的重复问题,因此最好在发布新问题之前先进行搜索。 :) 祝你好运!

似乎没有提到的一件事似乎运作良好。

Ajax 调用成功:

 success: function (response) {
     
     if("redirect" in response){

         window.location.href = response["redirect"];

    }
 }

您在视图中使用它而不是使用 HttpResponseRedirect

return JsonResponse({"redirect":'/customer/buyer'}, status=200)

暂无
暂无

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

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