Django提交表单->重定向到新页面->自动更新新页面

Django submit a form->redirect to a new page->auto update new page

本文关键字:gt 新页面 更新 提交 表单 Django 重定向      更新时间:2023-09-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,成功后会发生什么?视图中的return语句是如何在成功中捕获的,页面是如何显示的?我需要使用javascript和AJAX,因为一旦加载了新页面,我就需要在同一页面上显示连续的更新。那么,基本上我该如何使用javascript和Django用上面的代码实现重定向到新页面呢?任何帮助都将不胜感激!

在您的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/';

我希望这能有所帮助。