简体   繁体   中英

Render page after XMLHttpRequest POST

I'm having a hard time rendering a page after a XMLHttpRequest POST.

On my client side I do the following:

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

and server side:

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

Using the above code doesn't redirect to the info page. What am I doing wrong?

Please note that I don't want my user to see the query msg in his browser navigation bar but just /info .

you can't redirect pages from server side when performing ajaxes, what you can do is to change the url from client side when condition is in a state you wish to , any way you can redirect from client by using below command .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM