用PHP回显javascript是不好的做法吗 [英] Is it bad practice to echo javascript with php

查看:76
本文介绍了用PHP回显javascript是不好的做法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Listener类的php应用程序,该类基本上只是使用jquery设置ajax请求(下面的示例)。但是由于某种原因,回显javascript似乎不够优雅。更好的做法是为传递给javascript的代码构建单例类(这可能会引入耦合),或者像我现在所做的那样仅回显脚本?

I have a php application that makes use of a Listener class, which basically just sets up an ajax request with jquery (example below). But for some reason, echoing the javascript just seems inelegant. Is it better practice to build a singleton class for the javascript to be passed to (which could introduce coupling) or to just echo the script like I'm doing now?

这是我在做什么的代码段。

Here's a code snippet of what I'm doing.

<?php

        $script = "
                    <script>
                    $(document).ready(function(){
                        $('".$trigger."').".$action."(function() {
                        ".$js_variables."
                            var ajax_load = '';
                            var loadUrl = '".$this->controller_path."';
                            var action = $(this).attr('id');

                            $('".$this->parent."')
                            .hide(2)
                            .html(ajax_load)  
                            .load(loadUrl, {action: action, ".$post_mapper."})
                            .fadeIn(800);
                        });
                    });
                </script>
        ";

      echo $script;

?>

编辑:使用单例类还可以使我使用 $(document).ready()或快捷方式版本 $(function(){})一次,而不是每次添加一个侦听器,但是我不确定这是否值得额外的时间和精力...有什么想法吗? / p>

Using a singleton class would also allow me to use $(document).ready() or the shortcut version $(function(){}) only once instead of every single time I add a listener. But I'm not sure if this is worth the extra time and effort... Any ideas?

推荐答案

mm-都是我的偏好...我通常会这样做,因此我的文本编辑器将能够确定ja​​vascript和

mm it's all preference... I generally would do it like this so my text editor would be able to determine what's javascript and what's PHP so it wouldn't make my eyes bleed trying to look at non-code-colored text.

<script>
    $(document).ready(function(){
        $('<?php echo $trigger ?>').<? echo $action ?>(function() {
            <?php echo $js_variables ?>
            var ajax_load = '';
            var loadUrl = '<?php echo $this->controller_path ?>';
            var action = $(this).attr('id');

            $('<?php echo $this->parent ?>')
                .hide(2)
                .html(ajax_load)  
                .load(loadUrl, {action: action, <?php echo $post_mapper ?>})
                .fadeIn(800);
            });
    });
</script>

这篇关于用PHP回显javascript是不好的做法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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