/*** Http://www.yiiframework.com/wiki/394/javascript-and-ajax-with-yii JavaScript and Ajax with Yii translated by PHP Engineer Http://blog.csdn.net/phpgcs 1. Official JS Wrappers 1.1 Form validation 1.2 Cgridview 1.3 cjui* classes 1.4 Partial update with AJAX and CHtml 1.5 Extensions that wrap JS to PHP classes 2. Writing Custom JS Code 2.1 requiring some JS libraries (jQuery and such) 2.2 Inline JS (embedded in the HTML page) 2.3 JS in an external file 2.5 Inline code or external file? 3. Final words ****/This document provides a thorough and comprehensive tutorial on how to use JS in Yii. Not to talk about how to use JS programming, but how to use the Yii way ... The first part introduces several examples about the hidden JS in Yii. The second part describes how to write the custom JS. 1, official JS wrappers even if the developer does not explicitly require the use of JS, Yii will often do so. Yii chooses jquery as the JS Library, and with the release of different yii versions, a new jquery library will be released accordingly. It is not recommended that you load other JQuery libraries yourself, which is likely to cause conflicts. 1.1 Form Validation Form validation in this case, JS is almost completely hidden. (Although JS is disabled by default after the Yii 1.1.11 version) There are 2 kinds of authentication using js:client-side validation, AJAX validation. 1.2 Cgridview default, Scaffolding GII Create PackageIt contains the admin page of Cgridview and the Index page containing the CListView. Oddly, Cgridview and CListView use Ajax by default. If you need to customize, there are several parameters in the API. AJAX is used by default to have pros and cons. The main controversy with the default behavior is that user actions do not appear in browser browsing history: For example, a user cannot return to the previous search filter. If this malady makes you want to disable AJAX in Cgridview, you can use ' ajaxupdate ' and false when initializing the Cgridview widget. 1.3 cjui* Classes The simplest way to use JS in Yii is to use Yii classes. The Jui plugin is already included in the PHP class. You can refer to the list of these classes. Each document page starts with an example. Cjuiwidget Zii.widgets.jui cjuiaccordion cjuiaccordion displays an accordion widget. Cjuiautocomplete Cjuiautocomplete displays an AutoComplete field. Cjuibutton Cjuibutton displays a button widget. Cjuidatepicker Cjuidatepicker displays a datepicker. Cjuidialog cjuidialog displays a dialog widget. Cjuidraggable cjuidraggable displays a draggable widget. Cjuidroppable cjuidroppable displays a droppable widget. Cjuiinputwidget Cjuiinputwidget is the base class for JUI widgets, can collect user InpuT. cjuiprogressbar Cjuiprogressbar displays a progress bar widget. Cjuiresizable cjuiresizable displays a resizable widget. Cjuiselectable cjuiselectable displays an accordion widget. Cjuislider Cjuislider displays a slider. Cjuisliderinput cjuisliderinput displays a slider. It can used in forms and post its value. Cjuisortable cjuisortable makes selected elements sortable by dragging with the mouse. Cjuitabs cjuitabs displays a tabs widget. There are also several JS classes in the Yii Web widgets, especially the CTreeView. 1.3.1 Pass the JS code to a PHP class. (Take Cjuiautocomplete as an example) in many cases, the basic example of using the Cjui class is not enough. We often also need to customize the JS action. For Cjuiautocomplete, we need to customize an instance with the following 2 features: A, auto-complete alternates are obtained asynchronously via AJAX, and B, the ID of the selected item is added to the form. The dynamic update of AJAX source and Yii HTML form cjuiautocomplete is an associative array. Its "source" primary key must be associated with AJAX, meaning that its value must be a JS function we can not simply write "function ():" Because this will be interpreted as a string value! The correct syntax is: "Js:fucntion (request, response) {...} "This" JS: "prefix tells Yii behind is the pure JS code, should be skipped. The principle of updating the form is the same as this: from within PHP, we pass a JS function that would read the item chosen. Here, the syntax is: ' SELECT ' = ' js:function '. 1.3.2 Full Example: The complete example interface shows only the project's names but the form passes a numeric ID. echo $form->hiddenfield ($model, ' userId '); $QUOTEDURL = Cjavascript::encode ($this->createurl (Array (' User/complete ')); $params = Array (' name ' = = ' usercomplete ', ' source ' = ' js:function ' (request, Response) {$.ajax ({ URL: "'. $quotedUrl. ' ", data: {" term ": request.term," fulltext ": 1}, Success:function (data) {response (data);} }); } ',///additional JavaScript options for the AutoComplete plugin//See
' Options ' = = Array (' minLength ' = ' 3 ',//min letters typed before we try to complete ' sel ECT ' = ' Js:function (event, UI) {jQuery (' #MyModel_userId '). Val (ui.item.id); return true; }", ), ); $this->widget (' Zii.widgets.jui.CJuiAutoComplete ', $params); This code outputs a hidden form field that holds the ID of the selected user. In the Select function, it is updated in select fuction through its HTML ID. Of course, this ID is dependent on the model's name. It's often a "modulename_attributename" form, but you should check your HTML form to make sure. The more flexible code should use Chtml::resolvenameid () to figure out the ID. A few points will be said later. A, in Ajax parameters, "data" should not be a string such as "fulltext=1&term=" +request.term. B, if you need to mix PHP values in "data", use Cjavascript::encode (). C, the URL of the AJAX call is built in PHP because this is the only portable scenario. /** * Propose completions for a term (AJAX). */Public Function Actionajaxcomplete () {if (! Yii_debug &&! Yii::app ()->request->isajaxrequest) {throw new Chttpexception (' 403 ', ' Forbidden access.'); } if (Empty ($_get[' term '])) {throw new chttpexception (' 404 ', ' Missing ' term ' GET parameter. '); } $term = $_get[' term ']; $filters = Empty ($_get[' exclude ')? Null: (int) $_get[' exclude '); Header (' Content-type:application/json; charset= ' UTF-8 '); Echo Json_encode (User::completeterm ($term, $exclude)); Yii::app ()->end (); The key lines read the GET "term" parameter, send the JSON header, and encrypt the result with JSON. If your code is not utf-8, you should use a slower-performing Yii static method Cjson::encode () instead of Json_encode () the static method in the above method User::completeterm () should return an array (Array ("id" =>xx, "value" =>xx, "label" =>XX), Array (...), array (...), ...) 1.4 Local refreshes with AJAX and CHtml there are 2 static methods in Yii Chtml::ajaxlink () Chtml::ajaxbutton () The following code would replace T He content of the HTML element of ID "My-profile" with the output of a call to the action "ajaxcontent" of the Controller "Profile". echo chtml::ajaxlink (' Update profile ', Array (' profile/ajaxcontent ', ' id ' = + $id),//YiI URL array (' Update ' = ' #my-profile ')//jQuery selector); Of course, in this case, the action "profile/ajaxcontent" must output HTML, although not a full HTML page. If you prefer to return a structured data and parse it in JS, you can replace "update" with a "success", as follows://The data received could looks like: {"id": 3, "MSG": "No error Found"} Array (' success ' = ' js:function ' (data) {$ ("#newid"). Val (data.id); $ ("#message"). Val (data.msg); } ') The easiest way to output JSON is to use Cjson::encode (). 1.5 Extensions that wrap JS to PHP classes in addition to the official Yii class, many extension provide JS features. Some extensions are just some wrappers, trying to make it easier for Yii to integrate with some JS plugins. If you are having some special features, please refer to the JS extensions list. /**** 2. Writing custom JS code translated by PHP engineer Http://blog.csdn.net/phpgcs ****/before writing your custom code, don't forget to check if there is a PHP wrap for your needs Pers such as, JUI Widgets Web Widgets JS Extensions 2.1 load JS Library. Requiring some JS libraries (jQuery and such) some JS libraries are released with Yii. When the PHP code needs to fit will automatically load. If you want to make sure that they load properly, you can use://Load jQueryUI (and also jQuery which is REquired by jQueryUI) Yii::app ()->clientscript->registercorescript (' Jquery.ui '); By default, Cclientscript::registercorescript () is loaded at the bottom of the page. Repeat writing two times without effect. 2.2 In line JS (embedded HTML JS) Inline JS (embedded in the HTML page) a small section of JS can be written in a PHP string. Yii::app ()->clientscript->registerscript (' UniqueID ', ' Alert ("OK"); For long JS code, without the support of syntax highlighting is really painful. But we can do this://raw JS file expanded into the page Yii::app ()->clientscript->registerscript (' UniqueID ', File_get_con Tents (' js/mycode.js ')); JS file with embedded PHP code Ob_start (); Include ' js/mycode.js '; Yii::app ()->clientscript->registerscript (' UniqueID ', Ob_get_clean ()); 2.3 Reference external JS of course, if a JS is always required, modify the layout template is a method, but when the JS file is only required in certain requests, you can://Load a file with an Aboslute and external URL Yii::app ()->clientscript->registerscriptfile (' http://example.com/a.js '); Load a file from "Js/custom.js" under the root of the application Yii::app ()->clientscript-> Registerscriptfile (Yii::app ()->baseurl. '/js/custom.js '); We can also use Cclientscript::P os_head, and other parameters to determine what is appropriate to load our script we can also use similar methods to load other files, such as CSS. 2.4 Loading external JS via assets in some cases, the JS code is not in a public directory. For example, when you develop a extension, all the files are under "Protected/extensions". At this point, you must first instruct Yii to post your JS code to the assets directory. Put The local directory into the application ' s assets $assetsUrl = Yii::app ()->assetmanager->publish (__dir__. ' /myassets '); Load a published file Yii::app ()->clientscript->registerscriptfile ($ASSETSURL. '/custom.js '); For more detailed usage reference Cassetmanager::p ublish () 2.5 with inline code or external files? In the loading JS, through a JS file loading will be more favored, there are many reasons, the most important is the readability is good. However, some tasks can not be done purely in JS. For example: There is no portable way to generate a Yii URL via JS. The path depends on the configuration of the Curlmanager. One solution is to put all the JS code into a file, used in PHP defined in the JS variable to complete. Yii::app ()->clientscript->registerscriptfile (Yii::app ()->baseurl. '/js/custom.js '); $vars = Array (' ajaxurl ' = = $this->createurl (' COmplete ', ' id ' = = $model->id,); Yii::app ()->clientscript->registerscript (' variables ', ' var myApp = '. Cjavascript::encode ($vars). ';'); In addition to Cjavascript::encode (), the static method Cjavascript::quote () is also useful. $url = $this->createurl (' app/ajaxprocessor '); $cs->registerscript (' var1 ', "var myurl = '". $url. "';"); Can break with some URLs $cs->registerscript (' var1 ', "var myurl = '". Cjavascript::quote ($url, True). "';"); 3. Conclusion Although you can write JS in a Yii application without caring about the PHP framework, there are many drawbacks. For example, the URL used by JS may go wrong when the first configuration changes. Or some of the pages will be due to Yii JS and the developer's JS Library conflict crashes. Although you can use the wrappers provided by YII, you should still be using 3: Cclientscript::registercorescript () cclientscript::registerscriptfile () Cclie Ntscript::registerscript ()
http://www.bkjia.com/PHPjc/532693.html www.bkjia.com true http://www.bkjia.com/PHPjc/532693.html techarticle /*** http://www.yiiframework.com/wiki/394/javascript-and-ajax-with-yii JavaScript and Ajax with Yii translated by PHP Engineer Http://blog.csdn.net/phpgcs 1. Official JS wrappers 1 ...