javascript - 将变量从 .CTP View 设置为 .JS

标签 javascript php html cakephp

我有一个非常烦人和无意义的问题,你准备好了吗? :x

好的,我们开始吧

实际上,我将一个特定的软件部署到 4 个环境中:开发、认证、预生产和生产。

昨天我在生产环境中收到错误报告。

问题是,当我尝试将一个 javascript 变量从我的 .ctp 设置到我的 .js 时,我的 .js 无法访问该变量,因此“设置”没有完成。奇怪的是,在其他环境(DES、CERT 和 PRE)中,它工作得很好,但在 PRO 中(对于某个谜题,它失败了)。

描绘问题:

  • translate.ctp

    <?php
    $translations = array();
    $translations['NO_DATA']=__('NODATA');
    $translations['VALUE']=__('VAL');
    $translations['WEBROOT'] = $this->webroot;
    
    $this->Js->set('translations',$translations); // <-- prepare 'translations' into JS as window.app.translations
    
    
    echo $this->Js->writeBuffer(array('onDomReady' => false)); // sets the variable 'translations' into the javascript (I only use writeBuffer once in this code and project)
    ?>
    
  • default.ctp

... header 、脚本加载和其他内容...

<?php echo $this->element('translate');?> // loads translations ctp
<?php echo $this->fetch('script'); ?>
  • ma​​in.js

     $(document).ready(function() {
                // window.app doesn't exists so the following instruction will trigger an error:
                var translatedNoData = window.app.translations['NO_DATA'];
     }
    

非常感谢你们,我希望上面的信息足够了。

最佳答案

我正在更新这篇文章以解决上面发布的“问题”。

上面的代码就OK了 $this->Js->set..$this->Js->writeBuffer是将 .CTP 中的变量作为全局变量直接设置到 .JS 中的正确方法(它将在 window.app 中设置)

问题是由用户插入的数据引起的。他在 DB 表的某个列中放置了一些 ' 而没有关闭它,该列的内容直接呈现到 HTML DOM 元素中,因此它粉碎了接下来的所有内容......

抱歉造成误会:)

关于javascript - 将变量从 .CTP View 设置为 .JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41237658/

相关文章:

javascript - 禁用 cookie 直至同意

python - 使用 python 在 HTML 中显示 JSON 数据

javascript - 添加 HTML、CSS 和 Javascript 到 Joomla 主页

javascript - 浏览器版本检测和重定向

php - 父类别和子类别下拉菜单

php - 另一个password_verify()问题可能与数据库相关

javascript - list 应用程序一次添加三项而不是一项

html - 将高度设置为与其旁边 float 的同级 div 相同?

javascript - 外部类调用 LitElement 组件方法(传递 html 模板),组件方法更新其 html 模板

javascript - jQuery 后台定位 vs CSS 动画定位的 bug 和效率