提取数值POST节点js

时间:2017-12-26 06:03:50

标签: jquery node.js ajax ejs

我正在尝试获取表单值以指示正在选择哪个项目。所以这里的主要目标是在后台运行此功能。但是,我需要提取该值,并根据该值运行函数。

这是我试图打电话的功能:

/*jshint esversion: 6 */

const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();
const passport = require('passport');
const db = require('../config/db');

router.post('/battle', function(req, res){

  if (!req.xhr) {
    res.redirect('/');
  } else {
    // Player Variables
    var userMhp = req.user.tough + req.user.str;
    var userHp = userMhp;
    var userDmg = req.user.str;
    var userDef = req.user.tough;

    //  Mob Variables
    **var mobid = req.body.mobs.value;**
    console.log(mobid);
    var mobMhp = Math.floor(mobid * 50);
    var mobHp = mobMhp;
    var mobDmg = mobid + 5;
    var mobDef = mobid;

    // Statistic variables
    var dmgdeltmob = 0;
    var dmgdeltuser = 0;
    var rounds = 0;

    // Strings
    // var userVictory = '';
    // var mobVictory = '';
    // var userDefeat = '';
    // var mobDefeat = '';

    //start battle loop
    while (userHp > 0 || mobHp > 0) {
      var userTurn = true;

      // Start BATTLE
      if (userTurn === true){
        dmgdeltmob = userDmg;
        mobHp = mobHp - dmgdeltmob;
        rounds += 1;
        userTurn = false;
      } else if (userTurn === false) {
        dmgdeltuser =  mobDmg;
        userHp = userHp - dmgdeltuser;
        rounds += 1;
        userTurn = true;
      }
    }

    // Start end of battle Calculations
    if (userHp <= 0) { // Defeat
      req.flash('error', 'you lost!');
    } else {
      req.flash('succes', 'you won!');
    }
  }
});

module.exports = router;

我把星线包裹在我遇到问题的星星中。我试图获取值的位置在下面的ejs文件中。

以下是我尝试这样做的ejs部分。

<form method="POST" action="/autos/battle">
  <select name="mobGet">
  <% for (var i = 0; i < mobs.length; ++i) { %>
      <option name="mobs" value="<%= mobs[i].id %>"><%= mobs[i].name %></option>
  <% } %>
  </select>
  <button id="battlebutton">Fight</button>
</form>

这是调用该函数的jQuery代码(不确定这是否真的需要,但这里是)

  $('#battlebutton').click(function(){
    $.ajax({
      type: 'POST',
      url: '/autos/battle',
      success: function (data) {
        ('#fight-results').html(data);
      },
      error: function (xhr, status) {
        alert('There was an error');
      },
    });
  });

0 个答案:

没有答案