将JavaScript添加到Django重定向(HttpResponse)

3

我在Django中使用重定向from django.shortcuts import redirect

我想要的是,在重定向前向用户显示一个JavaScript警报消息。

这是我目前的代码:

response = redirect("someUrl")
response.write('<script>alert(\'You must remove an item before adding another\');</script>')
response['location'] += "?active=" + "all"
return response

重定向可以实现,但JavaScript无法运行。我还尝试了其他方法。
response = HttpResponse('<script>alert(\'You must remove an item before adding another\');</script>')
return response

这会触发警报窗口,但我不确定如何添加与上述方法相当的重定向。

2个回答

3
您可以使用 js方法 window.location
url = 'someUrl'
resp_body = '<script>alert("You must remove an item before adding another");\
             window.location="%s"</script>' % url
return HttpResponse(resp_body)

2
你正在混淆前端和后端。当用户请求此视图时,服务器(通过Django的HTTPResponseRedirect)会发送一个302重定向HTTP响应,告诉浏览器重定向到另一个页面。这与正常的200响应(即普通的Django响应对象,而不是重定向)不同,您可以在其中包含javascript警报。
您需要在最初加载视图时显示该javascript,然后再返回重定向响应给用户。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接