yii_wiki_394_javascript-and-ajax-with-yii (在yii 中使用 javascript 和ajax)
Jun 21, 2016 am 08:49 AM/*** http://www.yiiframework.com/wiki/394/javascript-and-ajax-with-yii Javascript and AJAX with Yii translated by php工程師 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 ****/ 這篇文檔要給出一個(gè)徹底全面的教程,關(guān)于如何 在Yii 中使用 JS。并不是要講如何用JS編程, 而是如何用 Yii 的方式。。。 第一部分介紹幾個(gè)例子關(guān)于Yii中隱藏JS 的。 第二部分介紹如何寫(xiě)自定義的JS。 1, 官方JS wrappers 即使開(kāi)發(fā)者沒(méi)有明確要求使用JS , Yii 也經(jīng)常會(huì)這么干。 Yii選擇 JQuery 作為JS 庫(kù), 隨著不同Yii版本的發(fā)行, 相應(yīng)會(huì)發(fā)行 比較新的JQuery 庫(kù)。 不建議 大伙自行加載 其它的 JQuery 庫(kù), 很有可能會(huì)導(dǎo)致沖突。 1.1 表單驗(yàn)證 Form validation 這種情況下, JS 幾乎完全是隱藏的。(盡管從Yii 1.1.11 版本之后 JS 默認(rèn)是禁用的) 有2種 驗(yàn)證使用了JS: client-side validation, AJAX validation. 1.2 CGridView 默認(rèn)的, 腳手架 gii 創(chuàng)建 包涵了 CGridView 的 admin 頁(yè)面 以及 包含 了 CListView 的 Index 頁(yè)面。 奇怪的是, CGridView 和 CListView 默認(rèn)使用 Ajax。 如果你需要定制, 在API 中有幾個(gè)參數(shù)。 默認(rèn)地使用 AJAX 有 pros 和 cons 。跟默認(rèn)行為 最主要的爭(zhēng)議是 用戶 actions 不會(huì)在 瀏覽器瀏覽歷史中出現(xiàn): 如, 用戶無(wú)法 返回到之前的 search filter。 如果這個(gè)弊病 讓你 想要在CGridView 中禁用 AJAX 的 話, 你可以在 初始化 CGridView widget 時(shí) 用'ajaxUpdate' => false. 1.3 CJui* classes 在Yii 中使用 JS 最簡(jiǎn)單的辦法就是 使用 Yii classes。 Jui 插件已經(jīng)被包含在 PHP 類中了。你可以參照 這些類的列表。每一個(gè)文檔頁(yè)面都 是從一個(gè)例子開(kāi)始的。 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 that 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 be used in forms and post its value. CJuiSortable CJuiSortable makes selected elements sortable by dragging with the mouse. CJuiTabs CJuiTabs displays a tabs widget. 在 Yii 的 web widgets 中 也有 幾個(gè) JS 類, 特別是 CTreeView。 1.3.1 向一個(gè) PHP class 傳遞 JS 代碼。 (以 CJuiAutoComplete 為例 ) 在很多時(shí)候, 使用CJui 類 的基本例子 是不夠的。我們經(jīng)常還需要 自定義 JS 動(dòng)作。 拿 CJuiAutoComplete 來(lái)說(shuō), 我們需要 定制一個(gè)實(shí)例有以下2個(gè)特性: A, 自動(dòng)完成的備選項(xiàng) 都是通過(guò) AJAX 異步得到的, B, 被選中 的項(xiàng)目的 id 會(huì)被添加到 form 中。 AJAX source 和 Yii html form 的動(dòng)態(tài)更新 CJuiAutoComplete 的配置 是一個(gè) 關(guān)聯(lián)數(shù)組。它的 “source” 主鍵 必須跟 AJAX 關(guān)聯(lián), 意味著 它的 value 必須是 一個(gè) JS function 我們不可以簡(jiǎn)單的這樣寫(xiě) “function()..” 因?yàn)檫@會(huì)被解釋執(zhí)行為 一個(gè) string value ! 正確的語(yǔ)法是: "js:fucntion(request, response){...} " 這個(gè) “js:“前綴 告訴 yii 后面的 都是純 JS 代碼,應(yīng)該跳過(guò)。 更新 form 的原則跟這個(gè) 是一樣的 : from within PHP, we pass a JS function that will read the item chosen. 在這里 , 語(yǔ)法是: 'select' => "js:function(…". 1.3.2 完整的例子:The complete example 界面上只顯示 項(xiàng)目的 names 但是 form 傳遞的是一個(gè)數(shù)字 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 <http://jqueryui.com/demos/autocomplete/#options> '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); 這段代碼 輸出了一個(gè) 保存有 被選擇的 user 的 ID 的 hidden form field。 在select function 中, 通過(guò) 它的 html id , 在 select fuction 中更新。 當(dāng)然, 這個(gè) ID 是依存于 model 的名字的。經(jīng)常是 "ModuleName_AttributeName" 種形式 ,但是你應(yīng)該檢查你的 HTML form 來(lái)確定一下。 更靈活的代碼 應(yīng)該用 CHtml::resolveNameID() 來(lái)算出這個(gè)ID。 稍后將會(huì)說(shuō)幾個(gè) 要點(diǎn)。 A, 在 ajax 參數(shù)中, ”data” 不應(yīng)該是 像 "fulltext=1&term="+request.term 這樣的 string。 B, 如果你需要 在 ”data“ 中混合 PHP 值 ,使用 CJavaScript::encode(). C, AJAX call 的 url 是在 PHP 中組建的, 因?yàn)檫@是唯一的可移植的方案。 /** * 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(); } 重點(diǎn)的幾行 讀取 GET ”term“ 參數(shù), 發(fā)送 JSON頭, 用JSON 加密結(jié)果。 如果你的 編碼不是 utf-8 , 你應(yīng)該 用執(zhí)行效率稍慢的 Yii 靜態(tài)方法 CJson::encode() 而不是 json_encode() 上面的方法中 靜態(tài)方法 User::completeTerm() 應(yīng)該 返回一個(gè) array(array("id"=>xx, "value"=>xx, "label"=>xx), array(...), array(...), ...) 1.4 用 AJAX 和 CHtml 局部刷新 在Yii 中有2 個(gè)靜態(tài)方法 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 "ajaxcontent" of the controller "profile". echo CHtml::ajaxLink( 'Update profile', array('profile/ajaxcontent', 'id' => $id), // Yii URL array('update' => '#my-profile') // jQuery selector ); 當(dāng)然了,這種情況下, action "profile/ajaxcontent" 必須輸出 HTML, 盡管不是一個(gè)完整的 HTML 頁(yè)面。 如果你更喜歡 返回一個(gè) 結(jié)構(gòu)化數(shù)據(jù) 并在 JS 中 解析它, 可以 用一個(gè) "success" 替代 "update", 如下: // the data received could look like: {"id":3, "msg":"No error found"} array('success' => 'js:function(data) { $("#newid").val(data.id); $("#message").val(data.msg); }') 輸出JSON 最簡(jiǎn)便的方法就是 用 CJson::encode() 。 1.5 Extensions that wrap JS into PHP classes 除了官方的Yii 類, 許多 extension 都提供 JS 特性。 一些 extensions 僅僅是一些 wrappers , 試圖讓 yii 跟 某些 JS 插件的整合更方便。 如果你正在著一些特殊的特性, 請(qǐng)參照 JS extensions 列表 。 /**** 2. Writing custom JS code translated by php工程師 http://blog.csdn.net/phpgcs ****/ 在寫(xiě)你自定義的 代碼之前, 別忘了 檢查下 是否有適合你需求的 PHP wrappers 如, JUI Widgets Web Widgets JS extensions 2.1 加載 JS 庫(kù)。 Requiring some JS libraries (jQuery and such) 一些 JS 庫(kù)隨著Yii發(fā)行。當(dāng)PHP代碼需要的適合會(huì)自動(dòng)加載。 如果你想要確保它們正常加載, 可以用: // Load jQueryUI (and also jQuery which is required by jQueryUI) Yii::app()->clientScript->registerCoreScript('jquery.ui'); 默認(rèn)地, CClientScript::registerCoreScript() 會(huì)在頁(yè)面的底端加載。重復(fù)寫(xiě)兩遍沒(méi)有影響。 2.2 行內(nèi) JS(嵌入 HTML 的JS) Inline JS (embedded in the HTML page) 一小段的 JS 可以寫(xiě)在一個(gè) PHP string 中。 Yii::app()->clientScript->registerScript('uniqueid', 'alert("ok");'); 對(duì)于長(zhǎng)的JS 代碼, 沒(méi)有了 語(yǔ)法高亮的支持確實(shí)很痛苦。但我們可以這樣: // 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 引用外部的 JS 當(dāng)然了, 如果一個(gè) JS 總是需要的話, 修改 layout template 是一種方法, 但是當(dāng) JS 文件只有在某些 請(qǐng)求中 需要的話, 可以這樣: // 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'); 我們還可以用 CClientScript::POS_HEAD ,等參數(shù)來(lái) 決定 什么適合加載我們的 script 我們也可以 用類似方法 加載 其他的 文件, 如CSS 等。 2.4 通過(guò) assets 加載 外部JS 一些情況下, JS 代碼不在 一個(gè) public 的目錄下。 比如, 當(dāng)你開(kāi)發(fā)一個(gè) extension 后, 所有的 文件都 在 "protected/extensions" 之下。 這時(shí)候, 你必須首先 引導(dǎo) Yii 將你的 JS 代碼 發(fā)布到 assets 目錄下。 // 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'); 更多詳細(xì)用法參考 CAssetManager::publish() 2.5 用 inline代碼 還是 外部 文件? 在加載 js 時(shí), 通過(guò) 一個(gè) JS 文件加載會(huì)更讓人青睞, 有很多原因, 最主要的是可讀性好。 但是, 有些任務(wù) 不可以 純粹在 JS 中完成的。 舉例來(lái)說(shuō): 沒(méi)有 可移植的辦法 來(lái)通過(guò) JS 來(lái)生成一個(gè) Yii 的URL。 路徑 取決于 CUrlManager 的配置。 一種解決辦法就是 把所有的 JS 代碼放入一個(gè)文件, 用 在 PHP 中定義的 JS變量 來(lái)完成。 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) . ';'); 除了 CJavascript::encode(), 靜態(tài)的方法 CJavascript::quote() 也是有用的。 $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. 結(jié)束語(yǔ) 盡管 你可以 在不關(guān)心 PHP框架的 情況下在一個(gè) Yii 應(yīng)用中 寫(xiě) JS, 但是有很多弊端。 比如, JS 使用 的 URL 在首次配置改變時(shí), 可能會(huì)出錯(cuò)。 或者 一些頁(yè)面會(huì)因?yàn)?Yii 的 JS 跟 開(kāi)發(fā)者的 JS 庫(kù) 沖突 而崩潰掉。 盡管你可以不用 Yii 提供的 wrappers ,你仍然應(yīng)該使用 一下3個(gè): CClientScript::registerCoreScript() CClientScript::registerScriptFile() CClientScript::registerScript()

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ??and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to use JS and Baidu Maps to implement the map auto-complete search function. First, we need to understand what the map auto-complete search function is. Map auto-complete search is a method where after the user enters keywords in the input box, the map will automatically display relevant search results based on the keywords entered by the user. This function is very common in various map applications, such as searching for places, finding routes, etc. To use JS and Baidu Maps to implement the map auto-complete search function, we need several steps. Below I'll detail each step and provide corresponding code examples.

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.
