【问题标题】:NodeJS: Pass array and display the values on html pageNodeJS:传递数组并在html页面上显示值
【发布时间】:2016-01-05 11:50:08
【问题描述】:

我已经编写了下面的代码来使用 mongoose 从 mongodb 读取值并将其存储在数组中:

app.get('/StudentQuestionsPage',function(req,res){
    var allQuestionsArray = studentQuestions.find();
    var questions = [];
    allQuestionsArray.exec(function(err,questions){
        if(err)
            return cosole.log(err);
        questions.forEach(function(question){       
            var elem = new Object();
            elem["id"] = question.id;
            elem["quesStatement"] = question.quesStatement;
            elem["optionA"]=question.optionA;
            elem["optionB"]=question.optionB;
            elem["optionC"]=question.optionC;
            elem["optionD"]=question.optionD;

            questions.push(elem);
            console.log(elem)
        });
    }); 
    res.render(__dirname + '/StudentQuestionsPage.html',{questions:questions});
});

我必须将这一系列问题传递给一个 html 文件,然后我必须在 HTML 上显示内容。

我编写了下面的代码来在 HTML 上显示数组值,但它没有显示任何内容。 “console.log(elem)”可以在控制台打印值。

<html>
    <head>
        <title>Online Examination Portal</title>
        <h1>Questions</h1>
    </head> 
    <body>
        <div>   
        <form>
            <h2>Questions</h2>
                <ul>
                    <% questions.forEach(function(question) { %>
                    <li>Number: <%= question.id %> <br/> Text: <%= question.quesStatement %></li>
                    <% }); %>
                </ul>
        </form>
        </div>
    </body>
</html>

请告诉我如何从 nodejs 传递值并检索并在 html 上显示。

【问题讨论】:

    标签: javascript html node.js


    【解决方案1】:

    首先,将您的 questions 数组重命名为 allQuestions 或任何您想要的名称,例如 questions。您的.exec's 成功函数的参数名称与数组相同。因此,它将覆盖数组变量。 由于allQuestionsArray.exec 是一个async 函数,您应该从success 函数传递allQuestions 数组。重写你的代码如下...

    app.get('/StudentQuestionsPage',function(req,res){
    var allQuestionsArray = studentQuestions.find();
    var allQuestions = [];
    allQuestionsArray.exec(function(err,questions){
        if(err)
            return console.log(err);
        questions.forEach(function(question){       
            var elem = new Object();
            elem["id"] = question.id;
            elem["quesStatement"] = question.quesStatement;
            elem["optionA"]=question.optionA;
            elem["optionB"]=question.optionB;
            elem["optionC"]=question.optionC;
            elem["optionD"]=question.optionD;
    
            allQuestions.push(elem);
            console.log(elem)
        });
        res.render(__dirname + '/StudentQuestionsPage.html',{questions:allQuestions});
      }); 
    });
    

    【讨论】:

    • @Abhinav 您尝试过解决方案吗?有什么问题吗?
    • 是的,我试过了。但它不会在 HTML 上显示任何内容。
    • @Abhinav 我认为您的 HTML 存在一些问题。请检查一下。
    • 您的 html 页面加载正确吗?数据加载是否正确?请检查
    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 2021-08-09
    • 2017-04-17
    • 2019-03-24
    • 2013-05-06
    • 2017-06-04
    • 1970-01-01
    • 2018-01-07
    相关资源
    最近更新 更多