如何将TYPO3前端ajax映射到处理程序

问题描述 投票:0回答:2

如何从前端 TYPO3 页面向我的扩展中的函数或类方法进行 ajax POST?

我一直在使用 Extension Builder,默认情况下它似乎构建了一个 MVC 扩展,但我的扩展不需要是 MVC。

我可以在我的页面上放置 javascript ajax 调用,但如何将其映射到我的处理程序以及我的 ajax 函数中的 url 参数使用什么?此外,我如何保护网址?

我正在使用TYPO3 v7.6

ajax typo3-7.6.x typo3-extensions
2个回答
0
投票

在您的自定义扩展中调用 ajax,如下所示。

Javascript 用于调用 Ajax

function callAjax(param)
{
    $.ajax({
        async: 'true',
        url: 'index.php',
        type: 'GET',
        dataType: 'json',
        data: {
            eID: "Ajax_call",
            id:pageId,
            param:{
                param1:value
            }
        },
        success:function (data) {
            if (data.succ == 1) {
                $("#ad-success").show();
            }
        }
    });
}

localconf.php 文件

$TYPO3_CONF_VARS['FE']['eID_include']['Ajax_call'] = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('extension_key').'Classes/Ajax/EidDispatcher.php';

EidDispatcher.php 文件。

<?php

namespace vendor\extension_key\Ajax;

class EidDispatcher
{
    /**
   * @var \array
   */
    protected $configuration;

    /**
   * @var \array
   */
    protected $bootstrap;

    /**
   * The main Method
   *
   * @return \string
   */
    public function run()
    {
        return $this->bootstrap->run('', $this->configuration);
    }

    /**
   * Initialize Extbase
   *
   * @param \array $TYPO3_CONF_VARS
   */
    public function __construct($TYPO3_CONF_VARS)
    {
        // $page = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('page');

        $ajaxRequest = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('tx_extension_key');

        // create bootstrap
        $this->bootstrap = new \TYPO3\CMS\Extbase\Core\Bootstrap();

        // get User
        $feUserObj = \TYPO3\CMS\Frontend\Utility\EidUtility::initFeUser();

        // set PID
        $pid = (\TYPO3\CMS\Core\Utility\GeneralUtility::_GET('id')) ? \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('id') : 0;

        // Create and init Frontend
        $GLOBALS['TSFE'] = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
            'TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',
            $TYPO3_CONF_VARS,
            $pid,
            0,
            true
        );
        \TYPO3\CMS\Frontend\Utility\EidUtility::initLanguage();
        \TYPO3\CMS\Frontend\Utility\EidUtility::initTCA();
        $GLOBALS['TSFE']->connectToDB();
        $GLOBALS['TSFE']->fe_user = $feUserObj;
        $GLOBALS['TSFE']->id = $pid;
        $GLOBALS['TSFE']->determineId();
        $GLOBALS['TSFE']->initTemplate();
        $GLOBALS['TSFE']->getConfigArray();
        $GLOBALS['TSFE']->settingLanguage();

        // Get Plugins TypoScript
        $TypoScriptService = new \TYPO3\CMS\Extbase\Service\TypoScriptService();
        $pluginConfiguration = $TypoScriptService->convertTypoScriptArrayToPlainArray(
            $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_extension_key*emphasized text*.']
        );
        // Set configuration to call the plugin
        $this->configuration = array(
            'pluginName' => 'plugin_name',
            'vendorName' => 'vendor_name',
            'extensionName' => 'extension_name',
            'controller' => 'controller',
            'action' => 'action',
            'params' => $ajaxRequest['param'],
            'mvc' => array(
                'requestHandlers' => array(
                    'TYPO3\CMS\Extbase\Mvc\Web\FrontendRequestHandler' => 'TYPO3\CMS\Extbase\Mvc\Web\FrontendRequestHandler'
                )
            ),
            'settings' => $pluginConfiguration['settings'],
            'persistence' => array (
                'storagePid' => $pluginConfiguration['persistence']['storagePid']
            )
        );
    }
}
global $TYPO3_CONF_VARS;
// make instance of bootstrap and run
$eid = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
    'vendor\ExtensionKey\Ajax\EidDispatcher',
    $TYPO3_CONF_VARS
);
echo $eid->run();

0
投票

据我所知,有多种方法可以为 TYPO3 中的前端提供 AJAX 端点:

eID

简单快速,但默认情况下不加载前端上下文。很多开发者都因错误使用而被烧伤。

如果我想做的不仅仅是普通的非 Extbase PHP 之外的任何事情,我不会使用它,因为“手动”构建 TYPO3 上下文很容易出错,而且工作方式随着版本的不同而改变。不过,如果您确实需要的话,能够控制引导可以提供性能改进的可能性。


类型编号

为您的代码提供标准的前端环境。对于 Extbase 插件,您可以在 TypoScript 中定义另一个 PAGE 对象,其中仅包含您的插件内容:

ajaxPage = PAGE # call it whatever you want
ajaxPage {
   typeNum = 9787 # use a unique, unused typeNum
   10 < tt_content.list.20.yourextension_yourpluginname
   config {
     disableAllHeaderCode = 1
     additionalHeaders = Content-type:text/html # or application/json, or... 
     xhtml_cleaning = 0 
     admPanel = 0 # suppress Typo3 from adding anything unwanted
     debug = 0 # suppress Typo3 from adding anything unwanted
     no_cache = 1 # control if the output should be cachable
  }
}

要通过 AJAX 调用您的插件,您需要将页面类型添加到 URL。 在 Fluid 中你可以像这样构建它:

{f:uri.action(action: 'youraction', pageType: 9787)} # add controller=, pluginName=, extensionName= as needed

EXT:typoscript_rendering

https://github.com/helhum/typoscript_rendering

这个扩展可以让您免于 typeNum 方法中的 TypoScript 配置,但保留了优势,特别是对于 AJAX 到 Extbase 操作。

编写完普通的 Extbase 插件后,您可以使用 ViewHelper https://github.com/helhum/typoscript_rendering/blob/master/Classes/ViewHelpers/Uri/AjaxActionViewHelper.php 获取 Extbase 操作的 AJAX URL。

流体示例:

xmlns:t="http://typo3.org/ns/Helhum/TyposcriptRendering/ViewHelpers" # ViewHelper namespace

{t:uri.ajaxAction(action: 'youraction')} # works just like the Fluid f:uri.ajax.action with the same parameters.

中间件(TYPO3 v9+):

这就是我前进的方向。

例如:在

EXT:<extension>/Configuration/RequestMiddlewares.php
中:

<?php

return [
    'frontend' => [
        '<vendor>/<package>/json-middleware' => [
            'target' => \Vendor\Package\Http\MyJsonMiddleware::class,
            'after' => [
                'typo3/cms-frontend/site',
                // this gives TypoScript, routing and languageAspect. 
                // If you don't need that, you can build lightning-fast
                // routes (like eID) by adding the Middleware higher up
                // in the stack.
            ],
        ],
    ],
];

您可以在自定义中间件中控制 HTTP 响应的任何方面(例如使用 E-Tag 的客户端缓存、访问控制等)。我更喜欢将中间件设置为仅处理 HTTP 部分的调度程序,并将数据生成委托给(非 Extbase)控制器类。 请参阅 TYPO3 中间件文档

© www.soinside.com 2019 - 2024. All rights reserved.