在node.js中的ajax post之后不会呈现HTML页面

我正在使用express.js。 我想要做的只是点击一个表格元素后redirect到一个HTML页面。 目前的输出是HTML源console.log(而不是redirect,然后解释为HTML页面)

我的点击function如下(ajax后)

<script> $(".table").click(function() { /* Act on the event */ $.ajax({ url: "/selectForm", type: "POST", data: {name : "John"}, cache: false, timeout: 5000, complete: function() { //called when complete console.log('process complete'); }, success: function(data) { console.log(data); console.log('process sucess'); }, error: function() { console.log('process error'); }, }); }); 

我的app.post如下简单;

  app.post('/selectForm',function(req,res){ res.redirect('hello.html'); }); 

我在Chrome浏览器中获得了HTML输出,但在浏览器中,我没有看到它redirect到hello.html。

你的res.redirect('hello.html')指令对AJAX请求没有任何影响。 AJAX是asynchronous的,所以请求将发送到服务器,响应将返回给浏览器,由您的JavaScript解释。

要在AJAX请求之后redirect到另一个页面,您需要在console.log('process complete')指令的下面提供一个额外的指令( window.location.replace('hello.html') )。

我也有同样的问题,我发现了另一种方法来解决它~~networking的JavaScript ….

 $.ajax({ url: '/test', type : 'POST', data: data, success : function(ret){ document.write(ret); }, error: function(err){ document.write(err.responseText); } }); 

和服务器代码是…

 app.post('/test$',function(req,res,next){ if(req.body.xxx != null){ res.render('test',{xxx:xxx}) }else{ var err = {}; err.status = 403; err.message = 'not allow'; next(err); } }); app.use(function(err, req, res, next) { res.locals.message = err.message; res.render('error'); }); 

你可以尝试一下…..