Home > Backend Development > PHP Tutorial > 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中文网
Release: 2023-03-01 06:02:01
Original
1381 people have browsed it

First go to the code:

This is the viewsite/reg.php

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

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);
Copy after login

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;
Copy after login

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);
Copy after login

is missing a parameter. The result is like this:

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

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)!

Related labels:
php
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template