javascript - 使用ajax和快速路由重定向到新的url

标签 javascript ajax express ejs

我在 auth.ejs 页面上有一个带有 id: 'tune-in' 的按钮,单击该按钮后应转到新页面 index.html。 ejs.

但是,当我单击该按钮时,index 页面未呈现。相反,我仍在 auth 页面上,但我确实在控制台中记录了“应显示调入主页”消息。

在 html (ejs) 页面上( View 文件夹 > auth.ejs)

  document.getElementById('tune-in').addEventListener('click', function() {
    $.ajax({
      type: 'GET',
      url: '/tune-in',
      success: function(){
        console.log("should display tune-in home page");
      }
    });
}, false);

Controller 文件夹> authController.js

  app.get('/tune-in', function(req, res){
    res.render('index');
  });

View 文件夹>index.ejs 这只是一个常规的 html 页面,应该在点击时呈现。

编辑: index.js

var express = require('express');
var cookieParser = require('cookie-parser');

// userController takes care of rendering the view and
// routing requests to the server
var authController = require('./controllers/authController');
var userController = require('./controllers/userController');

var app = express();

app.set('view engine', 'ejs');
app.use(express.static('./public'))
   .use(cookieParser());

authController(app);

app.listen(process.env.PORT || 4000);
console.log("Listening to port 4000...");

最佳答案

如果我没记错的话,这就是你所需要的。

 document.getElementById('tune-in').addEventListener('click', function() {
$.ajax({
  type: 'GET',
  url: '/tune-in',
  success: function(data){
    console.log("should display tune-in home page");
    // data must be valid html
    $("html").html(data); // this line tells to load the data
    // $("#otherid").html(data);
   }
 });
}, false);

关于javascript - 使用ajax和快速路由重定向到新的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45132271/

相关文章:

javascript - 在 NodeJS 中更改 ReadStream 的文件名

javascript - 链接到功能的按钮在 html 中不起作用

javascript - promise 失败状态

javascript - 使用 jQuery Ajax 将 javascript 变量发送到 PHP 脚本

node.js - Express:如何在 app.get() 之外创建函数?

node.js - 类型错误 [ERR_UNKNOWN_FILE_EXTENSION] :

javascript - 等待编程滚动 Selenium /Protractor

javascript - 在 D3.js 中使用 geoJSON 数据绘制线条

jquery - 破坏 DataTable 时 IE 错误

javascript - 使用 React 进行多个 AJAX 请求