Post request implemented using yii.js in YII2 framework
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!

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

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



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
