>  기사  >  백엔드 개발  >  yii在视图里创建变量(保护php的代码),在js文件里调用之前创建的变量的代码实例

yii在视图里创建变量(保护php的代码),在js文件里调用之前创建的变量的代码实例

PHP中文网
PHP中文网원래의
2017-03-30 14:51:051321검색

先上代码:

这是视图site/reg.php里

    $cs = Yii::app()->getClientScript();
    $cs->registerScriptFile('/js/verify-code.js',CClientScript::POS_END);

这是layout/main.php里

$commonValue = json_encode([
            'SmsVerifycodeUrl' => Yii::app()->createAbsoluteUrl('site/SendSmsCode'),
            'WaitSecond' => WapMember::DEFAULT_INTERVAL,
    ]);
Yii::app()->clientScript->registerScript("var commonValue = $commonValue",CClientScript::POS_END);

这是verify-code.js文件里

var initSecond = (typeof CommonValue.WaitSecond) == "undefined" ? 180 : CommonValue.WaitSecond,
    waitSecond =initSecond,
    SmsVerifyCode = function(btn, form) { this.getBtn = btn; this.form = form;},
       SCF;

这是chrom浏览器报的错
verify-code.js:1 Uncaught ReferenceError: CommonValue is not defined

回复内容:

最后发现:
原来是在写

Yii::app()->clientScript->registerScript("var commonValue = $commonValue",CClientScript::POS_END);

少了一个参数。结果是这样子滴:

Yii::app()->clientScript->registerScript('commonValue',"var commonValue = $commonValue",CClientScript::POS_END);

commonValue 的 POS_END 简单地调整为 POS_HEAD.

或者确定 $commonValue 在main.php 中放到 render('reg.php') 之前, 两次 registerScript 是有先后顺序的

ps:

verify-code.js 能不能返回函数对象, 而不是在这个文件中引用全局变量
之前维护过这样的代码,恶心的一比

 以上就是yii在视图里创建变量(保护php的代码),在js文件里调用之前创建的变量的代码实例的内容,更多相关内容请关注PHP中文网(www.php.cn)!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.