【问题标题】:Is it possible to post from custom js to .module/custom.php/controller file and get response in custom js while developing custom module in drupal8?在 drupal8 中开发自定义模块时,是否可以从自定义 js 发布到 .module/custom.php/controller 文件并在自定义 js 中获得响应?
【发布时间】:2018-03-20 08:24:33
【问题描述】:

我在 drupal modules/mymodule/js/ 文件夹中的 custom.js 文件中有这个

  (function ($) {
  Drupal.behaviors.coorrency = {
    attach: function (context, settings) {

      jQuery.ajax({
            url: 'modules/mymodule/custom.php',
            type: "POST",
            success:  function(data){
                        console.log(data);
                    }
          });
    }
  }
})(jQuery);

我必须发布到 modules/mymodule/custom.php

<?php

echo "test";

?>

并从 custom.php 返回数据

【问题讨论】:

    标签: ajax drupal


    【解决方案1】:

    您可以通过创建一个控制器来监听该 ajax 调用来做到这一点

    my_module.routing.yml

    my_module.call_back:
          path: '/my_module/call_back'
          defaults:
            _controller: '\Drupal\my_module\Controller\DefaultController::callBack'
            _title: 'Call Back'
    

    控制器

    <?php
    
    namespace Drupal\my_module\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    
    /**
     * Class DefaultController.
     */
    class DefaultController extends ControllerBase {
    
      /**
       * Your Callback
       *
       */
      public function callBack() {
        return ["This is a test" ];
      }
    

    custom.js

    (function ($) {
      Drupal.behaviors.coorrency = {
        attach: function (context, settings) {
          jQuery.ajax({
            url: '/my_module/call_back',
            type: "POST",
            success:  function(data){
              console.log(data);
            }
          });
        }
      }
    })(jQuery);
    

    【讨论】:

    • 您不是在此处硬编码 URL,而是使用路由名称。你怎么能做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多