首页 > 解决方案 > How to re render a .ejs page with new data after ajax request

问题描述

I need to re render my homepage.ejs with new data on the server side after an ajax request. I know you can (somehow) re render the elements in the ajax callback but I was wondering if I could just re render my homapage.ejs since I have if statements that look for vacations, and current_user variables to set the right partialview.ejs

my ajax method:

function user_login(email, password) {
  var data = {};
  data.email_login = email;
  data.password_login = password;
  var message_header = $("#message_header");
  $.ajax({
    url: "/sign_in",
    method: 'POST',
    data: data
  }).done(function (res) {
    if (!res.success) {
      message_header.text("Incorrect email of password. Please try again.").css("color", "red");
      $("#username_textfield").val("");
      $("#password_textfield").val("");
    } 
    if (res.success) {
      console.log("user logged");
    }
  });

my server side (inside of a query callback)

get_all_vacations(function (error, vacations) {
  if (error) {
    console.log("error when getting vacations " + error);
    response.json({ success: false });
  } else {
    request.session.vacations = vacations;
    response.render('the_vacation.ejs', { vacations : vacations, current_user : new_current_user }, function() {
      response.json({success : true});
      console.log("in render method");
    });      
  }
});

i tried this but it does not work.

response.render('the_vacation.ejs', { vacations: vacations, current_user: new_current_user });

标签: javascriptnode.jsajaxexpressejs

解决方案


我认为根据您的代码编写方式,最简单的方法是window.location.reload();在登录成功时使用。

function user_login(email, password) {
  var data = {};
  data.email_login = email;
  data.password_login = password;
  var message_header = $("#message_header");
  $.ajax({
    url: "/sign_in",
    method: 'POST',
    data: data
  }).done(function (res) {
    if (!res.success) {
      message_header.text("Incorrect email of password. Please try again.").css("color", "red");
      $("#username_textfield").val("");
      $("#password_textfield").val("");
    } 
    if (res.success) {
      console.log("user logged");
      window.location.reload(); // <--- Cause the browser to reload the EJS
    }
  });

推荐阅读