2017-11-13 2 views
0

양식의 제출 이벤트에 대한 정보를 보내주기 위해 Ajax 호출을 구현했습니다. 그러나 삽입 쿼리가 작동하는 경우 특정 EJS 페이지에 renderredirect이 필요합니다. .AJAX POST 후 EJS 페이지를 렌더링합니다.

클라이언트

: 코드

그것은 Ajax 호출없이 작동하는 데 사용하지만, 지금은 클릭 할 때마다 그러나 페이지가 여기에

를 리디렉션하지 않는 쿼리가 작동 버튼을 제출하다
$(function() { 
    $('#addForm').on('submit', function(e) { 
     e.preventDefault(); 
     var titolo = $(this).find("#title").val(); 
     var time = $(this).find("#time").val(); 
     var tags = []; 
     var tagsCont = $(this).find(".chip"); 
     var tmpTag; 
     for(var i = 0; i < tagsCont.length; i++){ 
      tmpTag = $(tagsCont[i]).html().split('<')[0]; 
      tags.push(tmpTag); 
     } 
     var data = {titolo: titolo,time: time, tags: tags}; 
     var dataSend = $.ajax({ 
      type: "POST", 
      url: "/add", 
      data: JSON.stringify(data), 
      cache: false, 
      contentType: "application/json" 
     }); 
     dataSend.done(function(data){ 
      if(!data.status) 
       console.log("Error on data send"); 
      return; 
     }); 
     dataSend.fail(function (jqXHR, textStatus) { 
      console.log("Error on data send " + textStatus); 
      return; 
     }); 

    }); 
}); 

서버

var addPost = function(req, res, next) { 
    if(!req.isAuthenticated()){ 
     return res.redirect('/login'); 
    } 
    else { 
     var user = req.user; 
     if(user === undefined) 
      return res.redirect('login'); 
     else{ 
      user = user.toJSON(); 
      var timerPromise = null; 
      timerPromise = new Timer().fetch(); 
      console.log(req.body); 
      return timerPromise.then(function(model){ 
       var creation = new Date(); 
       var timerVal = req.body.time; 
       var ended = false; 
       var owner = user.id_user; 
       var title = req.body.titolo; 
       if(title.length <= 0) 
        return res.render('add.ejs', { 
         title: "Timing Time - Add Timer", 
         user: user, 
         errorMessagge: "Va dichiarato un titolo" 
        }); 
       var new_timer = new Timer({ 
        titolo: title, 
        time: timerVal, 
        created: creation, 
        ended: ended, 
        id_owner: owner 
       }); 
       new_timer.save(null, {method: "insert"}).then(function(model) { 
        if(!model) 
         return res.render('add.ejs', { 
          title: "Timing Time - ERROR", 
          user: user, 
          errorMessagge: "Problemi di inserimento del timer" 
         }); 
        return res.redirect('/'); 
       }); 

      }); 
     } 
    } 
} 

답변

1

응답이 ajax를 통해 수신되면 백엔드에서 어떤 URL로 리디렉션 되더라도 프런트 엔드에는 영향을 미치지 않습니다. 클라이언트 측에서 리디렉션을 수행해야합니다.

dataSend.done(function(data){ 
     if(!data.status) 
      console.log("Error on data send"); 
     else 
      location.href = '/'; 
     return; 
    }); 
관련 문제