首页 > 解决方案 > 从 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

谁能告诉我如何实现这一目标?谢谢

标签: javascriptdjangoajaxxmlhttprequest

解决方案


这适用于转移到我必须添加这一行的不同网址

  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})
        
      )

推荐阅读