【问题标题】:Django Redirect to a view with ajax callDjango 使用 ajax 调用重定向到视图
【发布时间】:2020-07-27 05:06:21
【问题描述】:

我有一个 Django 应用程序。在其中,当我想在不影响前端的情况下操作后端时,我对函数使用了一些 Ajax 调用。

在一个功能中,我想将用户重定向到主页。

我有:

def some_function(request, param_one):
    other_function(request.user, param_one)
    return redirect('mypage:home')

在 JS 中我有:

$.ajax({
        type : "GET",
        url : '/url to my function/',
        error: function(){
            console.log('Error complete');
        }
});

我发现我在 chrome 开发者工具中找到了正确的页面

但是什么都没有发生……所以 js 得到了 HTML 页面但没有渲染它。

【问题讨论】:

  • 如果要重定向,为什么还要使用 Ajax?为什么不直接使用标准表单并从那里返回重定向?
  • 你可以在ajax调用中返回url,如果它依赖于处理的数据。否则你可以在成功函数中调用window.location = "http://example.com";
  • 在服务器端重定向,不会改变用户当前页面,因为它是一个ajax调用,如果你想这样重定向,那么正如@DavitTovmasyan所说,不要做ajax,只需提交表格原样。
  • 我使用 Ajax 调用,因为逻辑更复杂,...只有当某些特定的急性,重定向应该发生,否则返回数据到视图,...

标签: javascript django ajax redirect django-views


【解决方案1】:

希望对你有帮助

def some_function(request, param_one):
    other_function(request.user, param_one)
    return render(request,'mypage:home')

JS

$.ajax({
        type : "GET",
        url : '/url to my function/',
        success: function (response) 
        {
            document.getElementById("response").innerHTML = response; 
            #replace the id of div where you want to show fetched data
        }
        error: function(){
            console.log('Error complete');
        }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多