Home  >  Article  >  Backend Development  >  Yii creates variables in the view (protecting PHP code), and calls the code instance of the previously created variable in the js file.

Yii creates variables in the view (protecting PHP code), and calls the code instance of the previously created variable in the js file.

PHP中文网
PHP中文网Original
2017-03-30 14:51:051321browse

First go to the code:

This is the viewsite/reg.php

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

This is the 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);

This is the verify-code.js file

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

This is the error reported by the chrom browser
verify-code.js:1 Uncaught ReferenceError: CommonValue is not defined

Reply content:

Finally found:
It turned out to be writing

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

is missing a parameter. The result is like this:

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

CommonValue's POS_END is simply adjusted to POS_HEAD.

Or make sure $commonValue is placed before render('reg.php') in main.php. The two registerScripts are in order

ps: Can

verify-code.js return functions or objects instead of referencing global variables in this file?
I have maintained such code before, it is disgusting

The above is the code example of Yii creating variables in the view (protecting PHP code) and calling the previously created variables in the js file. Please pay attention to more related content PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn