How to use jQuery with the Yii framework.?

2019-03-16 12:51发布

How to use jquery/javascript in yii?,

How to use my Script in yii?

Why is this any different from using jQuery in any other way?

3条回答
smile是对你的礼貌
2楼-- · 2019-03-16 13:03

This is a sample script that I just used in my app development:

<?php
$js = "
$('body')
  .on('click', '#cancelCreateInductionTemplate, #closeDialogBox', function (e) {
    // Close #openDialog
    e.preventDefault();
    $('#openDialog').dialog('close');
  });
";
Yii::app()->clientScript->registerScript('cancelCreateInductionTemplate', $js, CClientScript::POS_READY);
?>
查看更多
欢心
3楼-- · 2019-03-16 13:04

using Yii’s registerScript to load our jQuery, which if used normally looks like this:

$(document).ready(function(){
    alert('hello');
    // Enter code here
});

Now if we use Yii’s Script like this:

<?php
    Yii::app()->clientScript->registerScript('helloscript',"
        alert('hello');
    ",CClientScript::POS_READY);
?>

You will see that you need to pass 3 things to the Yii::app()->clientScript->registerScript function, firstly a script name, which is not really important; it must just bee unique from any other script name on the same page. LINK

查看更多
祖国的老花朵
4楼-- · 2019-03-16 13:15

How to use jquery in yii?

As you stated above you can either register a new script block or you can register a new external script file. You cna also register assets within plugins which will take entire JS folders and combine them into your app.

So there are many ways to use JQuery in Yii.

How to use my jquery in yii

JQuery comes pre-bundled and activated with JQuery and the JQuery library itself is considered a core script so there is no real need to put your own JQuery in.

You can overwrite the built in JQuery with your own by putting:

$cs = Yii::app()->clientScript;
$cs->scriptMap = array(
'jquery.js' => Yii::app()->request->baseUrl.'/js/jquery.js',
'jquery.yii.js' => Yii::app()->request->baseUrl.'/js/jquery.min.js',
);
$cs->registerCoreScript('jquery');
$cs->registerCoreScript('jquery.ui');

Something like that somewhere within either your layout, action or view. I prefer to put this within the layout and manage my own JQuery version personally.

Why is this any different from using jQuery in any other way?

Mainly due to standardisation and interoperability of the framework and its components. Coming pre-bundled with built in hooks for JQuery UI widgets and JQuery elements in general makes the framework much easier to build reusable and clean JS objects for use in your app.

Also I like JQuery so it makes sense for it to come pre-bundled in my opinion. However this is not a call to arms for JQuery being the only JS library/framework out there and you should really consider which is best for you before you choose.

查看更多
登录 后发表回答