javascript - 从 xmlhttprequest 后调用转移到不同的 url
问题描述
我有一个像这样的 xmlhttprequest 方法,它成功地从谷歌登录获取数据,之后我需要将数据发布到登录视图。在服务器端使用 python 和 django。
<form name="Login" method="POST" id="loginForm" action="/login">
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
alert("Token*"+id_token); //this gets executed
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhr.open('POST', '/login');
xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
alert("*******Token*"+id_token)
try
{
xhr.send('idtoken=' + id_token);
}
catch (e)
{
alert("*"+e.toString)
console.log('send() error: ' + e.toString());
return false;
}
视图.py
在视图中我定义了一个登录方法()
def login(request):
if request.method=='POST':
#process the request and send the data to another page with some additonal parameters
role=user_role
email=user_email
fullname=user_name
return render(request, 'ba/dashboard.html', {'role':role,'email':email,'fullname':fullname})
发布请求完成后,页面不会转移到 dashboard.html 页面,它只停留在同一个登录页面上。我希望它使用给定的参数传输到dashboard.html 页面。
这是发布完成后控制台输出没有GET请求通过
[09/Feb/2021 15:53:05] "POST /login HTTP/1.1" 200 4742
谁能告诉我如何实现这一目标?谢谢
解决方案
这适用于转移到我必须添加这一行的不同网址
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
**window.location.href="/home"** //I had hoped is there any other way to achieve without using this
}
为了传递参数,我从 post 方法执行此操作并进入 onreadystatechange,如上所示:
return HttpResponse(
json.dumps({'role':user_role,'email':user_email,'fullname':user_name})
)
推荐阅读
- cmake - CMake添加以“* .a”结尾的文件
- julia - 在 Julia 中保存到 pdf 文件的问题
- python - 试图列出带有特定反应表情符号的“投票最多”的消息
- javascript - 获取顶部容器组件的问题。extjs
- mysql - MySQL UNIQUE KEY 和 FOREIGN KEY 相同的列未创建
- macos - 运行“远程调试器”时出错:无法打开调试器端口(localhost:5005):java.net.ConnectException“连接被拒绝(连接被拒绝)”
- progressive-web-apps - PWA 可以在移动设备中使用外部存储和内部存储吗?
- c - 选择排序算法能否像冒泡排序一样提前终止循环?
- javascript - 如何在 Edge 中添加 polyfill 以支持 finally()?
- php - 在多维数组中使用大括号