所以我想从我的node.js后端对我的前端html文件进行更改。我该怎么办? (非常感谢任何带有示例的建议)
这是我想要改变的地方:
router.post('/change', function(req, res){
console.log(req.body.list);
//modify html DOM here!!
//preferably using jQuery
})
答案 0 :(得分:4)
您不能以我认为您尝试的方式从节点方面进行修改。您可以将响应发送回客户端,并且在该响应上,您可以触发一个函数(您可以在JQuery中编写),该函数将更改DOM并保存需要在本地存储中更改的内容...这里是一个例子......
//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>