基于服务器端逻辑认为有害的回应Javascript代码吗? [英] Is echoing Javascript code condtionally based on server-side logic considered harmful?

查看:65
本文介绍了基于服务器端逻辑认为有害的回应Javascript代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样:

 < script> 
setSomeStuffUp();

<?php if($ otherStuffNeedsToBeDone === true){?>

doSomeOtherStuff();

<?php}?>

breakSomeStuffDown();
< / script>

在工作中遇到类似于模板的事情(Smarty),所以它看起来更清洁一些 - 但不是太多!还回应了一些用于诸如jQuery选择器等事物的模板变量,以及其他一些令人不愉快的小东西。



有什么正确的方法可以做到这一点?通过AJAX将需要用于JS中逻辑的数据加载为JSON? HTML数据属性?



关于它的一些问题只是味道不好,糟糕,不好。



谢谢大家。

解决方案

使用X语言生成Y语言代码是一种不好的做法。 尝试解耦这两种语言,例如,像这样:

 < script type =text / javascript > 
var data = {
id:<?php echo $ id?>,
...
};
$ b $(document).ready(function(){
$(#+ data.id).on(click,function(){
/ *做点什么* /
});
});
< / script>

这样,PHP只关心填充数据结构,而JavaScript只关心消费数据结构。

Like this:

<script>
    setSomeStuffUp();

    <?php if ($otherStuffNeedsToBeDone === true) { ?>

         doSomeOtherStuff();

    <?php } ?>

    breakSomeStuffDown();
</script>

Came across something like this at work- done with templating (Smarty), so it looks a bit cleaner- but not by much! Also echoes some template variables used for things such as jQuery selectors, and other little unpleasant-looking bits.

What's the proper way to do this? Load the data that needs to be used for logic in the JS as JSON via AJAX? HTML data attributes?

Something about it just smells bad, bad, bad.

Thanks everyone.

解决方案

It is bad practice to use language X to generate code in language Y.

Try "decoupling" the two languages, for example, like this:

<script type="text/javascript">
  var data = {
    id: "<?php echo $id ?>",
    ...
  };

  $(document).ready(function(){
     $("#" + data.id).on("click", function(){
       /*do something*/
     });
  });
</script>

This way, PHP only cares about populating the data structure and JavaScript only cares about consuming the data structure.

这篇关于基于服务器端逻辑认为有害的回应Javascript代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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