使用window.location.replacement()重定向AJAX成功

Redirection on AJAX success using window.location.replace()

本文关键字:重定向 AJAX 成功 window location replacement 使用      更新时间:2023-09-26

我正在尝试在成功的ajax调用上重定向页面,下面的代码运行良好,

$.ajax(
      {
      type: "POST",
      url: path,
      data: response1,
      contentType: "application/json",
      success: ->
                 window.location.replace("http://172.16.17.141:81/configuration/manage_users")
      });

这种方法的问题是,我给出的路径是固定的,我想要类似的东西

$.ajax(
      {
      type: "POST",
      url: path,
      data: response1,
      contentType: "application/json",
      success: ->
                 alert(window.location.host + "/configuration/manage_users")#Gives right path
                 window.location.replace(window.location.host + "/configuration/manage_users")   
                 #Does not work, I even tried window.location.host.toString()
      });

页面不使用上述方法重定向,而是重定向到"about:blank",而不是URL。

任何帮助都将不胜感激。

问题是我没有指定协议

window.location.replace(window.location.protocol + "//" +
                                  window.location.host + "/configuration/manage_users")

运行良好,我发现

window.location = window.location.protocol + "//" +
                                         window.location.host + "/configuration/manage_users"

更适合重定向。

通常您可以在服务器上执行此操作。您必须响应正确的HTTP标头。您的后端技术是什么?在node.js中,它看起来是这样的:

var host = 'http://172.16.17.141:81'
response.writeHead(302, {
  'Location': host + '/configuration/manage_users'
});
response.end();

这样行吗?

$.ajax
  type: 'POST'
  url: path
  data: response1
  contentType: 'application/json'
  success: ->
    window.location = "//#{window.location.host}/configuration/manage_users"