2017-06-20 135 views
1

我在XMLHttpRequest POST後很難渲染頁面。XMLHttpRequest POST後渲染頁面

在我的客戶端我做到以下幾點:

var http = new XMLHttpRequest(); 
var url = window.location.origin + "/mypath"; 

http.open("POST", url, true); 

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/json"); 

http.onreadystatechange = function() { 
    if (http.readyState == 4 && http.status == 200) { 
     console.log('you should be redirected or render a new page); 
    } else { 
     // Handle error 
    } 
} 
http.send(JSON.stringify(myParams)); 

和服務器端:

router.get("/info", (req: Request, res: Response) => { 
    res.render('info', {msg: req.query.msg}); 
}) 
router.post("/mypath", (req: Request, res: Response, next) => { 
    res.send(res.redirect(url.format({ 
     pathname:"/info", 
     query: {msg:'my message'} 
    }))); 
}) 

使用上面的代碼不重定向到信息頁面。我究竟做錯了什麼?

請注意,我不希望我的用戶在他的瀏覽器導航欄中看到查詢msg,但只需/info

+0

查看我的回答 –

回答

1

在執行ajax時,您無法從服務器端重定向頁面,您可以做的是在條件處於您希望的狀態時從客戶端更改url,您可以使用以下命令從客戶端重定向。

let baseUrl = window.location.origin 
window.location.replace(baseUrl + '/info');