ajax - 在 drupal8 中开发自定义模块时,是否可以将自定义 js 发布到 .module/custom.php/controller 文件并在自定义 js 中获取响应?

标签 ajax drupal

我在 drupal module/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返回数据

最佳答案

您可以通过创建一个 Controller 来监听 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'

Controller

<?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" ];
  }

自定义.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);

关于ajax - 在 drupal8 中开发自定义模块时,是否可以将自定义 js 发布到 .module/custom.php/controller 文件并在自定义 js 中获取响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379369/

相关文章:

javascript - 使用ajax调用php并返回多个变量?

jquery - 在 sails js 中的 ajax 调用中渲染部分

java - CentOS Java 应用程序出现 SELinux 错误

javascript - 德鲁巴 : Flowplayer API not loaded

drupal 主题的 css 到 "right to left"

drupal - 使用 UC 和 PayPal WPS 的匿名结账不起作用

javascript - PHP、JavaScript AJAX

jquery - 使用 Ajax 对每个 mysql 结果进行排序

Javascript ajax insidehtml 返回 html 输入

Drupal 表单模板建议