亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數據從后端(nodejs)傳遞到前端javascript

將數據從后端(nodejs)傳遞到前端javascript

一只甜甜圈 2022-06-05 16:52:35
我的數據庫(MongoDB)中有數據,我正在從數據庫中查找數據并將其保存到數組中。當在頁面上單擊按鈕時,我想將該數據發送到我的 JavaScript 文件并使用 DOM 在頁面上顯示它。頁面加載時,我正在從 DB 中找到數據:app.get('/', function(req, res) {    var ipsumTextArray = [];    Ipsum.find({}, function(err, allIpsumTexts) {        if (err) {            console.log(err);        } else {            allIpsumTexts.forEach(function(ipsum) {                ipsumTextArray.push(ipsum.text);            });        }        res.render('home');    });});在我的另一個 JavaScript 文件中,我希望這個函數從數據庫中獲取數據并做任何我想做的事情。function randomIpsum(text) {    text.value = 'text from database'; // text is textarea where I want to show text}
查看完整描述

1 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

您需要使用參數進行渲染。


app.get('/', function(req, res) {

    var ipsumTextArray = [];

    Ipsum.find({}, function(err, allIpsumTexts) {

        if (err) {

            console.log(err);

        } else {

            allIpsumTexts.forEach(function(ipsum) {

                ipsumTextArray.push(ipsum.text);

            });

        }

        res.render('home', { arr: ipsumTextArray });

    });

});

在前端(視圖):


var arr= {{ arr }}


function randomIpsum(text) {

    //text.value = 'text from database'; // text is textarea where I want to show text

    text.value = arr[0]

}

或者


您可以從 nodejs 發送純文本。


app.get('/', function(req, res) {

    var ipsumTextArray = [];

    Ipsum.find({}, function(err, allIpsumTexts) {

        if (err) {

            console.log(err);

        } else {

            allIpsumTexts.forEach(function(ipsum) {

                ipsumTextArray.push(ipsum.text);

            });

        }

        res.send(ipsumTextArray);

    });

});

您可以在前端使用 jQuery 獲取數據。


<button id="btn">Get Data</button>


$("#btn").on("click", function(){

    $.get("/", function(data){

        randomIpsum(text, data)

    })

})


function randomIpsum(text, data) {

    //text.value = 'text from database'; // text is textarea where I want to show text

    text.value = data

}


查看完整回答
反對 回復 2022-06-05
  • 1 回答
  • 0 關注
  • 916 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號