2016-10-26 128 views
0

当我发送xhr post请求到我的服务器。它回复302重定向,但我只能记录整个重定向html,并且无法让浏览器重定向到新的url。如何从xhr请求重定向

server.js

const Hapi = require('hapi'); 
const Inert = require('inert'); 

const server = new Hapi.Server(); 
const port = 8888; 

server.connection({ port }); 

server.register([ Inert ],() => { 
    server.route([ 
    { 
     method: 'get', 
     path: '/', 
     handler: (request, reply) => { 
     reply.file('index.html'); 
     } 
    }, 
    { 
     method: 'get', 
     path: '/login', 
     handler: (request, reply) => { 
     reply.file('login.html'); 
     } 
    }, 
    { 
     method: 'post', 
     path: '/login', 
     handler: (request, reply) => { 
     reply.redirect('/'); 
     } 
    } 
    ]); 

    server.start(() => { 
    console.log('Server running on ', server.info.uri); 
    }); 
}); 

的index.html

<!doctype html> 
<html> 
    <body> 
    <h1> Home </h1> 
    <a href="/login"> go to login </a> 
    </body> 
</html> 

的login.html

<!doctype html> 
<html> 
    <body> 
    <button id="home">home</button> 
    <script> 
     function goHome() { 
     var xhr = new XMLHttpRequest(); 
     xhr.onreadystatechange = function() { 
      if(xhr.readyState === 4 && xhr.status === 200) { 
      console.log('Response: ', xhr.response); 
      } 
     } 
     xhr.open('post', '/login'); 
     xhr.send(); 
     } 
     document.getElementById('home').addEventListener('click', goHome); 
    </script> 
    </body> 
</html> 

有没有办法重定向到 '/' 没有做客户端?提前帮助

回答

1

感谢有没有办法重定向到“/”没有做客户端?

通过XMLHttpRequest的发起将得到将由XMLHttpRequest的被处理的响应的请求号。如果该响应是重定向,则将遵循该响应,并且XMLHttpRequest将处理对新请求的响应。

Ajax是在不离开页面的情况下从JS发出HTTP请求的行为。

如果你想离开页面,请不要使用Ajax。