我正在进行动态调查。他们将调查问题从给定调查GUID的数据库中提取。然后,从上面的查询中提取每个问题的questionGUID,然后从数据库中提取每个问题要使用的答案。我似乎无法将问题答案值传递到我的ejs文件中。

我认为这与查询函数的异步特性有关,但是我尝试了在here.on找到的多种解决方案。

我的route.js

function router() {
  // survey start page
  surveyRouter.get('/', function(req, res){
    var prms = req.query;
    res.render('surveyIndex', {prms:prms})
  });

  surveyRouter.get('/:surveyGuid', function(req, res){
    //empty array to put values in
      var questionValues = [];
      function storeQuestionValues(rows){
          questionValues= rows[0];
      // console.log(questionValues);
      }

    //surveyGUID hard coded into HTML link href
    //gets questions to use in ejs
    connection.query("CALL spGetSurveyQuestions(?);", req.params.surveyGuid, (err, rows, fields) => {
      if(err) throw err;

      //all questions
      var questions = rows[0]

      questions.forEach(function(question){
        //push results of stored procedure that gets question values by question GUID into empty array
        connection.query("CALL spGetSurveyQuestionValues(?);", question.QuestionGuid, (err, rows, fields) => {
          storeQuestionValues(rows);
          // console.log(questionValues);
        });
      });
      res.render('test', {questions : questions, questionValues : questionValues });
    });
  });

  return surveyRouter;
}



我的测试ejs文件

  <%include partials/header%>

<div id="masthead" class="container">
      <div class="row py-2">
        <div class="col-md-12">
          <h1 class=text-center> Satisfaction Survey</h1>
        </div>
      </div>
</div>

<form>
  <div class="containter">
    <div class="col-md-12">
      <%questions.forEach(function(question){%>
        <label><%= question.QustionSequence %>. <%= question.QuestionText %> </label></br>
          <% questionValues.forEach(function(questionValue){%>
           <p> <%= questionValue.AnswerText%></p>
            <%});%>
        <%});%>
    </div>
</div>
</form>


<%include partials/footer%>



如果将res.render()移到第二个查询函数中,则会出现标题错误,但是第一个问题的问题值会出现在每个问题下。因此,至少它会吐出一些东西。

现在,我只是想从问题值查询中获取任何要打印在每个问题下的内容,并担心以后在什么问题中包含哪些值。

最佳答案

我花了一些时间并提出了一些更聪明的方法,从而取得了进步。

  surveyRouter.get('/:surveyGuid/:questionSequence', function(req, res){
    var questionSequence = req.params.questionSequence;
    connection.query("CALL spGetSurveyQuestions(?);", req.params.surveyGuid, (err, results, fields) =>{
      var questions = results[0];
      if(questions[questionSequence - 1].QustionSequence == questionSequence){
        connection.query("CALL spGetSurveyQuestionValues(?);", questions[questionSequence - 1].QuestionGuid, (err, results, fields) =>{
          var questionValues = results[0];
          res.render('test', {questions: questions, questionSequence: questionSequence, questionValues: questionValues});
        });
      }
    });
  });

关于mysql - MySQL查询值不会传递到ejs文件。查询取决于先前查询的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57792261/

10-09 17:52
查看更多