Frage

I am using an express.js. What I would like to do is just redirect to an html page after a table element is clicked . Currently the output is the HTML source console.log ( instead of redirected and then intepreted as HTML page)

My click function as below ( ajax post)

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

});

My app.post as simple as below ;

 app.post('/selectForm',function(req,res){


 res.redirect('hello.html');
 });

I got the HTML output in chrome javascript console, but in browser I dont see it's redirect to hello.html.

War es hilfreich?

Lösung

Your res.redirect('hello.html') instruction will have no affect on an AJAX request. AJAX is asynchronous so the request will be made to the server and the response will be returned to the browser to be interpreted by your JavaScript.

To redirect to another page after an AJAX request, you will need to give an extra instruction (window.location.replace('hello.html')) beneath the console.log('process complete') instruction.

Andere Tipps

I aslo have the same problem,and i found another method to resolve it~~ web javascript....

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

and the server code is ...

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

you can try it.....

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top