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

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

PHP中文网
PHP中文网Original
2017-03-30 14:51:051323Durchsuche

先上代码:

这是视图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)!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn