【问题标题】:Django submit a form->redirect to a new page->auto update new pageDjango提交表单->重定向到新页面->自动更新新页面
【发布时间】:2015-12-11 07:22:26
【问题描述】:

好的,正如标题所描述的,我正在尝试创建一个网页(test.html),在提交表单后它应该将我重定向到一个新页面(比如 status.html)。在这个页面加载之后它应该显示提交任务的一些持续更新。当我尝试将其重定向到新页面时,我能够在单个页面上完成此操作,但我不走运。

test.html

<form action="status/" method="POST" id="start-form">
.....
<input type="submit" value="Start" class="tbutton">

views.py

def status_page(request):
print("Inside redirect")
return HttpResponseRedirect(request,'my_app/status.html')

url.py

url(r'^test/status/$', 'status_page'),

jav.js

$('#start-form').on('submit',function(event){
event.preventDefault();    
status(); 
}); 
function status() { 
$.ajax({
    url : "status_page/", // the endpoint
    type : "POST", // http method
    data:{' ': '',}, // data sent with the post req
headers: {Accept: "application/json"},  
   success : function(json) {
//on success display the rendered page,so what coding is needed here?   
},
    error : function(xhr,errmsg,err) {
//error handling code    }
    });
 }

在执行时不会加载新页面,但如果我绕过 javascript,则会执行表单操作并通过视图呈现新页面。但是使用 JavaScript,成功后会发生什么?视图中的返回语句如何在成功中捕获以及页面如何显示? 我需要使用 javascript 和 AJAX,因为一旦加载了新页面,我需要在同一页面上显示持续更新。那么基本上如何使用 javascript 和 Django 使用上述代码实现对新页面的重定向?任何帮助将不胜感激!

【问题讨论】:

    标签: javascript html django


    【解决方案1】:

    在您的views.py 中,HttpResponseRedirect 使用不正确。如果你想重定向到一个新页面,那么你应该使用,

    return HttpResponseRedirect('/url-where-you-want-to-redirect/')
    

    HttpResponseRedirect 需要 url 参数而不是模板名称。

    请看这里:https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponseRedirect

    更好的方法是从您的status_page 视图返回一个 JSON 响应,然后在 ajax 的success 方法中,您可以转到下一个 URL:

    window.location.href = '/url-where-you-want-to-redirect/';
    

    我希望这会有所帮助。

    【讨论】:

    • 好的,对于第一种方法,但是 url 参数如何映射到加载的实际模板。这会再次将您带回 Url.py,然后再次返回视图。对于第二种方法,如果我在 javascript 中成功给出 URL,它会再次返回 url.py 文件以搜索该特定 URL 的匹配视图,这看起来是一个循环,在哪里加载 URL 你去视图然后去回到 javascript,然后再次回到视图。对不起,我很困惑
    • 我假设在 test.html 页面中您正在通过 AJAX 调用 test/status/ 并且当响应到来时,您将其重定向到另一个 URL。我的理解正确吗?
    • 对于第一种方法,您需要有另一个视图并且需要从该视图呈现另一个模板。正如您所提到的,我相信这是对提交的任务进行一些持续更新的模板。
    猜你喜欢
    • 2019-03-14
    • 2014-03-10
    • 2016-01-09
    • 1970-01-01
    • 2017-08-17
    • 2021-07-18
    • 2016-01-15
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多