无论如何,是否有必要像在PHP中(嵌入文档中)那样在服务器端使用js?

时间:2018-07-27 21:31:04

标签: javascript php server-side

我既喜欢又讨厌PHP的一个功能是能够将代码嵌入HTML。好处是能够看到我的代码流。缺点是混乱的意大利面条式代码有时会变得难以阅读。

例如,我正在寻找可以将js代码作为预处理的服务器端代码在发送给客户端之前在后端执行的东西。该代码可以像PHP一样嵌入到我的HTML文档中。也许服务器端JS将被包装在特殊的分隔符中以表示它已被预处理。

<?js //start of preprocessed, server-side JS code

const hostname = "myhn";
const username = "root";
const passcode = "mypassword";
const dbname = "mydatabase";

var conn = new mysqli(hostname, username, passcode, dbname);
if (conn.connect_error) {

die();

} else {

let userId = 1;

const qry = "SELECT * FROM users WHERE user_id = ?";
const getUser = conn.prepare(qry);
getUser.bindParam('i',userId);
getUser.execute();
const result = getUser.fetchResult();

while(var row = result.fetchObject()){

    var firstName = row.firstName;
    var points = row.points;

}

?> //end of server-side JS code 

<p>Welcome, <a id="settings"><?js document.write(firstName); ?></a>. You have 
<?js document.write(points); ?> points. </p>

<script type="text/javascript">
    document.querySelector('#settings').addEventListener('click',()=>{

        window.confirm("Do you wish to alter your settings>");

    });

</script>

<?js 
}
?>

例如,这是否作为NodeJS的功能存在?

2 个答案:

答案 0 :(得分:0)

您可以使用 node.js ejs 项目: https://www.npmjs.com/package/ejs

在服务器端,您可以创建包含以下代码的页面(也称为视图):

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

您应该阅读其文档并尝试一下。

答案 1 :(得分:0)

为此,您必须将Node js与ejs或jade引擎一起使用:-

var modal = document.getElementById('modal-box');

$('.button-func').click(function(){
    $('.filter-box').animate({height:"toggle", opacity:"toggle"}, "slow");
    $('.header').animate({opacity:'.6'});
    $('.topnav').animate({opacity:'.6'});
    $('.add-filter').animate({opacity:'.6'});
    $('.main_home_box').animate({opacity:'.6'});
});

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
        $('.header').animate({opacity:'1'});
        $('.topnav').animate({opacity:'1'});
        $('.add-filter').animate({opacity:'1'});
        $('.main_home_box').animate({opacity:'1'});
    }
}