/*** Success.
/*** 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 into 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. It is not about how to program with JS, but about how to use Yii... The first section describes several examples about how to hide JS in Yii. The second part describes how to write custom JS. 1. Yii often does this even if developers do not explicitly require JavaScript. Yii selects JQuery as the JS Library. with the release of different Yii versions, a newer JQuery library will be released accordingly. We do not recommend that you manually load other JQuery libraries, which may lead to conflicts. 1.1 Form verification in this case, JavaScript is almost completely hidden. (Although JS is disabled by default after Yii 1.1.11) two types of verification use JS: client-side validation and AJAX validation. 1.2 By default, the scaffold gii creates the admin page of the CGridView and the Index page containing the CListView. The strange thing is that CGridView and CListView use Ajax by default. If you need to customize, there are several parameters in the API. By default, AJAX has pros and cons. The main controversy with default behaviors is that actions does not appear in the browser browsing history: for example, users cannot return to the previous search filter. If you want to disable AJAX in CGridView, you can use 'ajaxupdate' => false when initializing the CGridView widget. 1.3 CJui * classes the easiest way to use JS in Yii is to use Yii classes. The Jui plug-in has been included in the PHP class. You can refer to the list of these classes. Every document page starts with an example. CJuiWidget zii. widgets. jui CJuiAccordion displays an accordion widget. CJuiAutoComplete displays an autocomplete field. CJuiButton displays a button widget. CJuiDatePicker displays a datepicker. CJuiDialog displays a dialog widget. CJuiDraggable displays a draggable widget. CJuiDroppable displays a drop Pable widget. CJuiInputWidget is the base class for JUI widgets that can collect user input. CJuiProgressBar displays a progress bar widget. CJuiResizable displays a resizable widget. CJuiSelectable displays an accordion widget. CJuiSlider displays a slider. CJuiSliderInput displays a slider. it can be used in Forms and post its value. CJuiSortable makes selected elements sortable by dragging with the mouse. CJuiTabs displays a tabs widget. There are also several JS classes in Yii web widgets, especially CTreeView. 1.3.1 pass JS code to a PHP class. (Take CJuiAutoComplete as an example) in many cases, the basic example of CJui class is not enough. We often need to customize JS actions. Taking CJuiAutoComplete as an example, we need to customize an instance with the following two features: A. The automatically completed backup options are obtained asynchronously through AJAX, B, the id of the selected project is added to form. The configuration of dynamic update CJuiAutoComplete of AJAX source and Yii html form is an associated array. Its "source" primary key must be associated with AJAX, meaning that its value must be a JS function. we cannot simply write "function () like this ().. "Because this will be interpreted and executed as a string value! The correct syntax is: "js: fucntion (request, response) {...}". "js:" The prefix tells yii that all JS code is pure and should be skipped. The rule for updating form is the same as this: from within PHP, we pass a JS function that will read the item chosen. here, the syntax is: 'select' => "js: function (... ". 1.3.2 complete example: only The names of The project are displayed on The complete example interface, but The form passes a digital 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 'select' => "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 stores the ID of the selected user. In select function, it is updated in select function through its html id. Of course, this ID depends on the model name. It is often "ModuleName_AttributeName", but you should check your HTML form to determine. More flexible code should use CHtml: resolveNameID () to calculate this ID. I will talk about several key points later. A. in ajax parameters, "data" should not be A string like "fulltext = 1 & term =" + request. term. B. If you need to mix PHP values in "data", use CJavaScript: encode (). c. The url of AJAX call is set up in PHP, because this is the only portable solution. /*** Propose completions for a term (AJAX). */public function actionAjaxComplete () {if (! YII_DEBUG &&! Yii: app ()-> request-> isAjaxRequest) {throw new CHttpException ('20170101', 'Forbidden access. ');} if (empty ($ _ GET ['condition']) {throw new CHttpException ('20140901', 'Missing "term" GET parameter. ');} $ term = $ _ GET ['condition']; $ filters = empty ($ _ GET ['clude'])? Null: (int) $ _ GET ['clude']); header ('content-Type: application/json; charset = "UTF-8" '); echo json_encode (User :: completeTerm ($ term, $ exclude); Yii: app ()-> end ();} read The GET "term" parameter in several key lines and send the JSON header, encrypt the result in JSON format. If your encoding is not UTF-8, you should use the Yii static method CJson: encode (), which is less efficient than the static method User: completeTerm () in json_encode () returns an array ("id" => xx, "value" => xx, "label" => xx), array (...), array (...),...) 1.4 Local refresh with AJAX and CHtml there are two static methods in Yii: CHtml: ajaxLink () CHtml: ajaxbutton () the following code will replace the content of the HTML element of ID "my-profile" with the output of a call to the action "ajaxco Ntent "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, action "profile/ajaxcontent" must output HTML, although it is not a complete HTML page. If you prefer to return a structured data and parse it in JS, you can replace "update" with "success", as shown below: // the data encoded Ed cocould look 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 into PHP classes in addition to the official Yii class, many extension provides JS features. Some extensions are just some wrappers, trying to make it easier to integrate yii with some JS plug-ins. If you are using some special features, 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, do not forget to check whether there are any PHP wrappers suitable for your needs, such as JUI Widgets Web Widgets JS extensions 2.1 to load the JS Library. Requiring some JS libraries (jQuery and such) some JS libraries are released along with Yii. PHP code is automatically loaded when appropriate. If you want to ensure that they are loaded 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. Repeated writes are not affected. JavaScript (JS embedded in HTML) Inline JS (embedded in the HTML page) can be written in a PHP string. Yii: app ()-> clientScript-> registerScript ('uniqueid', 'Alert ("OK"); '); for long JS code, without syntax highlighting, it is really painful. But we can do this: // raw JS file expanded into the page Yii: app ()-> clientScript-> registerScript ('uniqueid', file_get_contents ('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 needed, layout template modification is a method, but when the JS file is only required in some requests, you can do this: // 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: POS_HEAD, and other parameters to determine what scripts are suitable for loading. we can also use similar methods to load other files, such as CSS. 2.4 loading external JS through assets in some cases, JS code is not in a public directory. For example, after you develop an extension, all files are under "protected/extensions. At this time, you must first guide Yii to publish your JS code to the assets directory. // Put the local directory into the application's assets $ assetsUrl = Yii: app ()-> assetManager-> publish (_ DIR __. '/myasset'); // Load a published file Yii: app ()-> clientScript-> registerScriptFile ($ assetsUrl. '/custom. js '); for more usage details, refer to CAssetManager: publish () 2.5 using inline code or external files? When loading js, loading through a JS file will be more favored, for many reasons, the most important thing is good readability. However, some tasks cannot be completed purely in JS. For example, there is no portable method to generate a Yii URL through JS. The path depends on the configuration of CUrlManager. One solution is to put all JS code into a file and use the JS variables defined in PHP. 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 ). ';'); besides 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. although you can write JS in a Yii application without worrying about the PHP framework, there are many drawbacks. For example, an error may occur when the URL used by JS is changed for the first time. Or some pages will crash due to conflicts between Yii JS and the developer's JS Library. Although you do not need wrappers provided by Yii, you should still use three: CClientScript: registerCoreScript () CClientScript: registerScriptFile () CClientScript: registerScript ()