JQuery试图更改window.location错误地截断了查询参数

JQuery attempt to change window.location incorrectly truncating query parameters

本文关键字:参数 查询 错误 location window JQuery      更新时间:2023-09-26

我为了好玩而尝试JQuery,结果遇到了一堵砖墙。我正在尝试编写一个登录页面,我的想法是在jsp上创建一个表单,用户可以在其中输入登录id和密码,然后单击提交按钮。然后,JQuery方法会捕捉到这一点,然后对后端进行AJAX调用。然后,"success"方法应该将窗口对象的位置设置为由Ajax调用返回的值指示的新URL。仅供参考:我是一个后台人员,我已经涵盖了这部分。我的问题是,尽管我调用后端并获得所需的数据。然后,我尝试用一个包含单个查询参数的URL设置一个新的窗口位置(以允许应用程序知道用户是谁),当我到达基本URL时,它几乎可以工作,但没有查询参数(尽管基本URL的末尾有一个"?")

这是我的JQuery代码:

    </script>
      $(document).ready(function(){
        submit( function() {
          var id = $("#login_id").val();
          var pwd = $("#password").val();
          var uri = "`http://localhost:8080/SW_Server/rest/admin/login`";
          $.ajax({
            async: false,
            url: uri,
            type: 'GET',
            dataType: "json",
            success: function(data) {
              var session = data.session;
              newLoc = data.redirect+"?"+data.session
              // Prevent the form's default submission.
              preventDefault();
              // Prevent event from bubbling up DOM tree, prohibiting delegation
              event.stopPropagation();
              window.location.replace(encodeURIComponent(newLoc));
            },
          error: function(jqHHR, textStatus, errorThrown) {
            alert("textStatus: "+textStatus+"'nerror: "+errorThrown);
            // Prevent the form's default submission.
            event.preventDefault();
            // Prevent event from bubbling up DOM tree, prohibiting delegation
            event.stopPropagation();          
          }
        });
      });
    </script>

当我执行此操作时,我的后端当前返回data.redirect=http://localhost:8080/test.jsp和data.session=session_id=3,我在警报中看到了这一点(对我来说是hooray),但当调用window.location.replace(newLoc)时,它会转到http://localhost:8080/test.jsp?,不带查询参数。我一整天都在摇头。如何才能使新页面正确获取查询参数?

问候,

Tim

尝试将值分配给location而不是

window.location = data.redirect;

你尝试过其中的一些吗:

$(document).ready(function(){
        $("#loginForm").submit( function(event) {
          var id = $("#login_id").val();
          var pwd = $("#password").val();
          var uri = "http://localhost:8080/SW_Server/rest/admin/login";
          alert("uri: "+uri);
          $.ajax({
            async: false,
            url: uri,
            type: 'POST',
            dataType: "json",
            data: { "id":id, "pwd":pwd },
            success: function(data) {
                $('#loginForm').attr('action',data.redirect);
                $('#loginForm').submit();
            },
            error: function(jqHHR, textStatus, errorThrown) {
              alert("textStatus: "+textStatus+"'nerror: "+errorThrown);      
            }
          });

           // Prevent the form's default submission.
           event.preventDefault();
           // Prevent event from bubbling up DOM tree, prohibiting delegation
           event.stopPropagation();
           //and also    
           return false;
        });
});