Home  >  Article  >  Backend Development  >  Post request implemented using yii.js in YII2 framework

Post request implemented using yii.js in YII2 framework

不言
不言Original
2018-05-04 11:30:181508browse

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(
   &#39;删除&#39;,
   [
     &#39;delete&#39;,
     &#39;id&#39; => $id,
   ],
   [
     &#39;data&#39; => [
       &#39;confirm&#39; => &#39;你确定要删除吗?&#39;,
       &#39;method&#39; => &#39;post&#39;,
     ],
   ]
 )
 ?>
 // 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(&#39;data-form&#39;) ? $(&#39;#&#39; + $e.attr(&#39;data-form&#39;)) : $e.closest(&#39;form&#39;),
      method = !$e.data(&#39;method&#39;) && $form ? $form.attr(&#39;method&#39;) : $e.data(&#39;method&#39;),

      // 其他省略

    },

    // 其他省略
  };
  // 初始化模块
  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(&#39;method&#39;),
        message = $this.data(&#39;confirm&#39;),
        form = $this.data(&#39;form&#39;);

      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(&#39;click.yii&#39;, pub.clickableSelector, handler)
      .on(&#39;change.yii&#39;, 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 = $(&#39;<form/>&#39;, {method: method, action: action});
var target = $e.attr(&#39;target&#39;);
if (target) {
  $form.attr(&#39;target&#39;, target);
}
if (!/(get|post)/i.test(method)) {
  $form.append($(&#39;<input/>&#39;, {name: &#39;_method&#39;, value: method, type: &#39;hidden&#39;}));
  method = &#39;post&#39;;
  $form.attr(&#39;method&#39;, method);
}
if (/post/i.test(method)) {
  var csrfParam = pub.getCsrfParam();
  if (csrfParam) {
    $form.append($(&#39;<input/>&#39;, {name: csrfParam, value: pub.getCsrfToken(), type: &#39;hidden&#39;}));
  }
}
$form.hide().appendTo(&#39;body&#39;);

// 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn