如何在客户端使用服务器端的数据?

时间:2020-07-24 01:53:23

标签: javascript express ejs

这是我的app.js

var products = [
   {description: "Hi"},
   {description: "Hi2"}
]

app.get('/', function (req, res){
    res.render("home.ejs");
})

app.get('/checkout', function (req, res){
    res.render('checkout.ejs', {products:products});
});

app.post('/checkout', function(req, res){

    var description = req.body.description;
    var newProduct = {description};
    products.push(newProduct);

    res.redirect('/');
});

这是我的home.ejs

<form action="/checkout" method = "POST">
                    <p class = "item-description">LP Snake Pocket Tee</p>
                    <input type="hidden" name = "description" class = "item-description-post">
                    <div class="btn-group btn-add mr-2" role="group" aria-label="Second group">
                        <button class="btn btn-success btn-add-cart">ADD TO CART</button>
                    </div>
</form>

这是我的hoje.js文件,该文件基本上用我想要的内容填充了我的输入值,因此我可以将其作为POST输入发送

var item = $(".item-description")[0].innerHTML;
var postInput = $(".item-description-post").val(item);

现在我是我的checkout.ejs文件,我可以做类似的事情,并打印我的所有产品(仅到目前为止的说明)

                <% products.forEach(function(product){ %>
                    <p> <%= product.description %> </p>
                <% }); %>

我的问题是,如何在单独的.js文件中执行同一操作?

我的checkout.ejs中确实有一个javascript文件

<!-- JAVASCRIPT -->
<script type = "text/javascript" src="./checkout.js"></script>

但是该文件无法访问我的阵列“产品”。这是有道理的,因为我的后端仅将数据发送到我的ejs文件,因此,基本上,如何将数据“产品”从我的app.js文件发送到我的checkout.js文件? :)))

1 个答案:

答案 0 :(得分:0)

您不能。

注意:您只能将数据从.ejs文件传递到.js文件,而不能以其他方式传递。它不起作用,因为.ejs在服务器端呈现,而.js在客户端运行。我假设您在服务器端使用EJS 为什么:

EJS模板将在开始执行js之前在服务器上呈现(它将在浏览器上启动),因此无法返回到服务器并要求页面上已发送到页面的先前更改。浏览器。

相关问题