This article mainly introduces the post request implemented using yii.js in the YII2 framework. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
yii2 provides a lot Help classes, such as Html, Url, Json, etc., can easily implement some functions. Let’s briefly talk about this Html. I often use it when writing views in yii2, and I used it again when rewriting a page today. What makes it easier to use is that it not only generates a simple HTML tag, but also can easily implement a post request when combined with yii2's own static resource file yii.js.
yii2 has encapsulated these functions. You only need to call its methods in the appropriate place. It can be said that yii2 is a framework that can be used out of the box. You can use it to quickly implement a Required functions: For example, place a delete button on the page, click the button to send a post request, and a confirmation dialog box will pop up. If there is no yii\helpers\Html class and yii.js, then you need to write a lot of js/jquery to achieve this function. If you use yii2, the following code can be implemented:
// html代码 <?= Html::a( '删除', [ 'delete', 'id' => $id, ], [ 'data' => [ 'confirm' => '你确定要删除吗?', 'method' => 'post', ], ] ) ?> // html代码
It will generate the following html code in the page:
<a href="delete?id=1" rel="external nofollow" data-confirm="你确定要退出吗?" data-method="post">删除</a>
Click this button and a dialog box will pop up. After confirming the deletion, it will be sent post request. So how is this post request sent? So far, I haven't written a piece of js code.
The yii2 framework hides the details of technical implementation, and the post request is implemented in yii.js. In yii.js, the window.yii object is defined and the initModule method of the window.yii object is initialized:
window.yii = (function ($) { var pub = { // 定义了处理事件的方法,比如下面这个: confirm: function (message, ok, cancel) { if (window.confirm(message)) { !ok || ok(); } else { !cancel || cancel(); } }, handleAction: function ($e, event) { var $form = $e.attr('data-form') ? $('#' + $e.attr('data-form')) : $e.closest('form'), method = !$e.data('method') && $form ? $form.attr('method') : $e.data('method'), // 其他省略 }, // 其他省略 }; // 初始化模块 initModule: function (module) { if (module.isActive !== undefined && !module.isActive) { return; } if ($.isFunction(module.init)) { module.init(); } $.each(module, function () { if ($.isPlainObject(this)) { pub.initModule(this); } }); }, // 初始化方法 init: function () { initCsrfHandler(); initRedirectHandler(); initAssetFilters(); initDataMethods(); }, return pub; })(window.jQuery); window.jQuery(function () { window.yii.initModule(window.yii); });
The above initDataMethods() will call the pub.handleAction method:
function initDataMethods() { var handler = function (event) { var $this = $(this), method = $this.data('method'), message = $this.data('confirm'), form = $this.data('form'); if (method === undefined && message === undefined && form === undefined) { return true; } if (message !== undefined) { $.proxy(pub.confirm, this)(message, function () { pub.handleAction($this, event); }); } else { pub.handleAction($this, event); } event.stopImmediatePropagation(); return false; }; // handle data-confirm and data-method for clickable and changeable elements $(document).on('click.yii', pub.clickableSelector, handler) .on('change.yii', pub.changeableSelector, handler); }
You can see that this method will obtain the data attribute value of the a tag generated above, and then hand it over to handlerAction for processing. handlerAction handles various requests by dynamically generating a form, and finally submits it by triggering the submit event.
// 其他省略 $form = $('<form/>', {method: method, action: action}); var target = $e.attr('target'); if (target) { $form.attr('target', target); } if (!/(get|post)/i.test(method)) { $form.append($('<input/>', {name: '_method', value: method, type: 'hidden'})); method = 'post'; $form.attr('method', method); } if (/post/i.test(method)) { var csrfParam = pub.getCsrfParam(); if (csrfParam) { $form.append($('<input/>', {name: csrfParam, value: pub.getCsrfToken(), type: 'hidden'})); } } $form.hide().appendTo('body');
// Others omitted
PS: It is very convenient to use a framework for projects, but after using the framework for a long time, it is easy to forget the basic technology. It is still necessary to lay a good foundation, so that no matter what framework is used, it will not be used in a fog.
Related recommendations:
Yii2 framework integration Xunsearch search engine method
Yii2 framework PHPExcel export Excel file method
The above is the detailed content of Post request implemented using yii.js in YII2 framework. For more information, please follow other related articles on the PHP Chinese website!

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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