如何使用node.js更改前端html [英] How to change front-end html using node.js

查看:73
本文介绍了如何使用node.js更改前端html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想从我的node.js后端对前端html文件进行更改.我该怎么办? (任何带有示例的建议将不胜感激)

So I want to make changes on my front-end html file from my node.js backend. How would I do so? (Any suggestions with examples would be greatly appreciated)

在这里我要更改它:

router.post('/change', function(req, res){
    console.log(req.body.list);
    //modify html DOM here!!
    //preferably using jQuery
})

推荐答案

您不能以我认为您尝试的方式从节点一侧进行修改.您可以将响应发送回客户端,然后在该响应上触发一个函数(您可以用JQuery编写),该函数将更改DOM并将需要更改的内容保存在本地存储中...这是一个例子...

You can't modify from the node side in the way that I think your're trying to do. You can send back a response to the client side, and on that response, you can trigger a function ( that you can write in JQuery ) that will change the DOM and save what needs to be changed in local storage ... here is an example ...

//server.js
router.post('/change',function(req,res){

    // the message being sent back will be saved in a localSession variable
    // send back a couple list items to be added to the DOM
    res.send({success: true, message: '<li>New list item number 1</li><li>New list item number 2</li>'});
});

这是前端...

//index.html
//body
<h1>Hello World</h1>
    <ul>
        <li>List item 1</li>
         //li items with class change will be changed on button click
        <li class='change'>List item 2</li>
        <button class="trigger">Trigger Change</button>
    </ul>

<script>

   //if we have data stored in the session variable, then use the data to change the DOM text
    if(window.localStorage.permanentData){
        $('li.change').replaceWith(window.localStorage.permanentData);
    }

    //change DOM function
    function changeDom(){
        //ajax call
         $.ajax({
                  url: 'http://localhost:8080/change',
                  method:'POST',
                  data: {list: "some info"}
                }).done(function(data){
                    //if we have a successful post request ... 
                    if(data.success){
                        //change the DOM &
                        //set the data in local storage to persist upon page request
                        localStorage.setItem("permanentData", data.message);
                        var savedText = localStorage.getItem("permanentData");
                        $('li.change').replaceWith(savedText);

                        return;
                    }
                }).fail(function(){
                   //do nothing ....
                    console.log('failed...');
                    return;
                });
        };

    //trigger change DOM  function
    $('.trigger').click(function(){
        changeDom();
    });

</script>

这篇关于如何使用node.js更改前端html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆