YII2 프레임워크에서 yii.js를 사용하여 구현된 게시 요청

不言
풀어 주다: 2023-03-25 11:12:02
원래의
1512명이 탐색했습니다.

이 글은 주로 YII2 프레임워크에서 yii.js를 사용하여 구현한 게시물 요청을 소개합니다. 이제 이를 공유합니다. 도움이 필요한 친구들이 참고할 수 있습니다.

yii2는 Html, Url, Json 등은 몇 가지 기능을 쉽게 구현할 수 있습니다. 이 Html에 대해 간단히 설명하겠습니다. yii2에서 뷰를 작성할 때 자주 사용했는데, 오늘은 페이지를 다시 작성할 때 다시 사용했습니다. 사용하기 쉬운 이유는 간단한 HTML 태그를 생성할 뿐만 아니라 yii2의 자체 정적 리소스 파일 yii.js와 결합하면 게시 요청을 쉽게 구현할 수 있다는 점입니다.

yii2는 이러한 기능을 캡슐화했습니다. 적절한 위치에서 해당 메서드를 호출하기만 하면 yii2를 사용하여 필요한 기능을 빠르게 구현할 수 있습니다. 예를 들어 페이지에 삭제 버튼을 배치하고 버튼을 클릭하여 게시물 요청을 보내면 확인 대화 상자가 나타납니다. yiihelpersHtml 클래스와 yii.js가 없다면 이 기능을 구현하려면 js/jquery를 많이 작성해야 합니다. yii2를 사용하면 다음 코드를 구현할 수 있습니다.

 // 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代码
로그인 후 복사

페이지에 다음 HTML 코드가 생성됩니다.

<a href="delete?id=1" rel="external nofollow" data-confirm="你确定要退出吗?" data-method="post">删除</a>
로그인 후 복사

이 버튼을 클릭하면 대화 상자가 나타나고 삭제를 확인한 후 게시물 요청이 표시됩니다. 전송된. 그렇다면 이 게시물 요청은 어떻게 전송되나요? 지금까지 나는 js 코드를 작성하지 않았습니다.

yii2 프레임워크는 기술적 구현의 세부 사항을 숨기고, 게시 요청은 yii.js에서 구현됩니다. yii.js에서는 window.yii 개체가 정의되고 window.yii 개체의 initModule 메서드가 초기화됩니다.

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);
});
로그인 후 복사

위의 initDataMethods()는 pub.handleAction 메서드를 호출합니다.

  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);
  }
로그인 후 복사

이 메서드를 볼 수 있습니다. 위에서 생성된 a 태그의 데이터 속성 값은 처리를 위해 handlerAction으로 전달됩니다. handlerAction은 양식을 동적으로 생성하여 다양한 요청을 처리하고 마지막으로 submit 이벤트를 트리거하여 양식을 제출합니다.

// 其他省略

$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;);
로그인 후 복사

//기타 생략

PS: 프로젝트에 프레임워크를 사용하면 매우 편리하지만 프레임워크를 오랫동안 사용하고 나면 기본 기술을 잊어버리기 쉽습니다. 어떤 프레임워크를 사용하더라도 안개 속에서 사용되지 않도록 좋은 기반을 마련하는 것이 여전히 필요합니다. Related Related 권장 사항 : xunsearch 검색 엔진의 프레임 워크 통합 방법 yii2 프레임 워크에서 phpexcel에서 Excel 파일을 내보내는 방법.

위 내용은 YII2 프레임워크에서 yii.js를 사용하여 구현된 게시 요청의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!