在何处以及如何放置Ajax调用Bootstrap模式内容

时间:2018-06-29 17:30:27

标签: javascript jquery node.js ajax bootstrap-modal

这是一个使用express,pug模板引擎和jquery的简单nodejs测试应用程序(下面添加了项目下载链接)。它提供一个带有两个数字输入的HTML表单,然后单击按钮即可将它们添加到服务器端(计算将由复杂的计算和数据库查询代替),并且以模态形式显示结果用户单击“提交”按钮时弹出的对话框。

目前非常基本:

screenshot of the test app

“添加经典数字”按钮将经典POST发送到服务器,并重新加载页面并添加结果。 “添加数字模式”将打开模式,但此刻不打开更多模式。

我坚持下去

  • 在何处放置函数,以便单击按钮可打开模式 AND发出服务器请求。
  • 要添加哪个函数以及带有哪些参数
  • 如何在服务器端app.js中处理请求。这是正常的POST路线吗?如何构造结果并将其发送回以便将其显示在模式中?

我试图在网上找到答案两天。我很高兴能为我指出正确的方向!

You can download the project folder, just "npm install" to install npm packages

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var fetchRouter = require('./routes/fetch');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/fetch', fetchRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js(路由器)

var express = require('express');
var router = express.Router();

var sum = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'This is the website', resultnumber: sum  });
});

//my stuff
router.post('/', function(req, res, next) {
  sum = parseFloat(req.body.nb1) + parseFloat(req.body.nb2)
  setTimeout(function(){ 
    res.render('index', { title: 'This is the website', resultnumber: sum  });
  }, 1500);

});

module.exports = router;

index.pug(模板)

extends layout

block content
  h1= title
  p Welcome to the Website

  form(method='POST' action='/')
    div.form-group
        label(for='nb1') Number 1:
        input#nb1.form-control(type='text', placeholder='Number 1' name='nb1')
    div.form-group
        label(for='nb2') Number 2:
        input#nb2.form-control(type='text', placeholder='Number 2' name='nb2')
    //button.btn.btn-primary(type='submit') Add these together
    button(type='submit' class='btn btn-info btn-lg') Add numbers classic

  button(type='button' class='btn btn-info btn-lg' data-toggle='modal' data-target='#myModal') Add numbers modal

  if(resultnumber != 0)
    p Sum:
    p #{resultnumber}

  // Modal
  #myModal.modal.fade(role='dialog')
    .modal-dialog
      // Modal content
      .modal-content
        .modal-header
          button.close(type='button', data-dismiss='modal') ×
          h4.modal-title Modal Result
        .modal-body
          p The result is supposed to be shown here. 
          script(type="text/javascript").
            var counter = 0
            console.log('das skript',counter++)
        .modal-footer
          button.btn.btn-default(type='button', data-dismiss='modal') Close

1 个答案:

答案 0 :(得分:0)

(使用jQuery时) 单击按钮后,对计算端点进行ajax调用。在收到来自端点的响应(您想要的结果)后,填充模态(使用jquery / js),然后显示模态。

示例代码: 服务器

//my stuff
router.post('/calculation', function(req, res, next) {
  sum = parseFloat(req.body.nb1) + parseFloat(req.body.nb2);
  res.status(200).json({ data : sum });
});

客户

$.ajax({
  url: "/calculation",
  type: "POST",
  dataType: "json",
  data: {
    nb1: num1,
    nb2: num2
  },
  success: function(json) {
    if(json.status == 200){
      // Show your modal. For example:
      $('.modal-body p').text(json.data); // Setting result to modal
      $('#myModal').modal('show'); // Showing modal
    }else {
      // Show error message
      $('#login-error').text("Invalid login.");
    }
  },

  error: function() {
    // Probably something wrong with the server.
    $('#login-error').text("Server error.");
  }   
});

希望这会对您有所帮助。