1

我对通过 ajax 调用我的模块操作有疑问。

我想通过 ajax 在我的模块中调用类。但对我来说最好的解决方案是打电话给清洁课。不扩展模块。

我不知道是否可以在不将文章添加到数据库并向他添加模块的情况下制作 url。

我使用 JQuery 代替 mooTools 但 js 框架并不重要。最重要的是通过 ajax 调用 php 类。

我有ajax模块。但是,如果我调用 ajax.php,则需要来自 tl_module 表的模块 ID。我不想用这张桌子。(Ajax 会经常调用,我宁愿不加载所有的 contao 机制。应该很快)。

提前感谢您的回答。

4

2 回答 2

2

我在 GitHub 问题中找到了 Contao >3.x 的答案(德语)

首先在你的前端模板中做:

<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";

$(document).ready(function(){

    $("#trigger").click(function(event){

      $.post(
            '<?php echo \Contao\Environment::get('requestUri')?>',
            data,
            function(responseText) {
                alert(responseText);

            }
        ).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
        event.preventDefault();
    });
});</script>

重要的是 -data["REQUEST_TOKEN"] -> 如果你不添加它,POST-request 将不会到达你的模块:

public function generate()
{   
    if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
       $this->myGenerateAjax();
       exit;
    }
   return parent::generate();
}

//do in frontend
protected function compile()
{
 ...
}
public function myGenerateAjax()
{      
    // Ajax Requests verarbeiten
    if(\Environment::get('isAjaxRequest')) {
        header('Content-Type: application/json; charset=UTF-8');
        echo json_encode(array(1, 2, 3));
        exit;
    }
}

如果您想通过 GET 执行 ajax,则不需要 reqest 令牌,而是 jquery funktion $get();

于 2014-11-17T14:21:41.793 回答
0

I would suggest you to use Simple_Ajax extension. In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls. It works with Contao 2.11 and you can call your php class with it. I find it much easier to use than ajax.php .

You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html

  1. Copy SimpleAjax.php to Contao's root folder.
  2. Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :

    class AjaxRequestClass extends System
    {
    
       public function AjaxRequestMethod()
       {
    
          if ($this->Input->post('type') == 'ajaxsimple' )
          {
             // DO YOUR STUFF HERE 
             exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
    
          }
       }
    }
    
  3. Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):

     $GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
    
  4. Now you can easily make ajax calls with simply posting data to SimpleAjax.php:

    $.ajax({
    type: "POST",
    url:  "SimpleAjax.php",
    data: { type: "ajaxsimple" },
    success: function(result)
    {
     //DO YOUR STUFF HERE
    }
    
于 2014-06-08T10:50:30.800 回答