Ajax Typo3 v10 中的请求:通过 typeNum 调用控制器操作

Ajax Request in Typo3 v10: Calling controller action via typeNum

我正在尝试通过 Javascript/Ajax 调用 Extbase 控制器操作。 版本是 Typo3 v10。控制器动作应该是 return JSON.

我已经创建控制器和动作如下:

namespace Thevendor\Theextension\Controller;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Http\Response;

class ExampleController
{
   /** @var ResponseFactoryInterface */
   private $responseFactory;

   public function __construct(ResponseFactoryInterface $responseFactory)
   {
      $this->responseFactory = $responseFactory;
   }
  
    public function doSomethingAction(ServerRequestInterface $request): Response
    {       
       error_log("controller action got called!");
       $data = ['result' => 42];
       $response = $this->responseFactory->createResponse()
          ->withHeader('Content-Type', 'application/json; charset=utf-8');
       $response->getBody()->write(json_encode($data));
       return $response;    
    }
}

接下来我在ext_localconf.php注册了一个插件:

\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
            'Thevendor.Theextension',
            'Testing',
            [
                \Thevendor\Theextension\Controller\ExampleController::class => 'doSomething',               
            ],
            // non-cacheable actions
            [
                \Thevendor\Theextension\Controller\ExampleController::class => 'doSomething',
            ]
        );

接下来,我创建了一个文件 /theextension/Configuration/Typoscript/setup.typoscript,如下所示:

example_page = PAGE
example_page {
    typeNum = 776776

    config {
        disableAllHeaderCode = 1
        additionalHeaders = Content-type:application/json
        xhtml_cleaning = 0
        debug = 0
        no_cache = 1
        admPanel = 0
    }
    10 < plugin.theextension_testing        
}

我正在通过在浏览器和 Postman 中访问以下 URL 来测试它:

/home?no_cache=1&pagetype=776776&tx_theextension_testing%5Baction%5D=doSomething&tx_theextension_testing%5Bcontroller%5D=Example&type=776776&cHash=f63ebddb3625ec605e51b6ba07cf0731

响应为 200 OK 且为空。未调用我的控制器操作中的行“error_log”。 如果我将 TypoScript 的最后一行更改为:

10 = TEXT
10.value = ExampleText

我确实得到了“ExampleText”returned。所以 TypoScript 定义、typeNUM 和上面 URL 的结果正在工作,但我无法让它调用控制器操作。我也试过: 10 < tt_content.list.20.theextension_testing 但结果是一样的。

有人能帮我指明正确的方向吗? 非常感谢您的帮助。

尝试在您的 TypoScript 代码中添加 pluginName、extensionName 和 vendorName。它应该是这样的:

ajaxSearch_page = PAGE
ajaxSearch_page {
    typeNum = 776776
    10 = USER
    10.userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
    10.extensionName= ExtensionName
    10.pluginName = PluginName
    10.vendorName = Vendor

   config {
      disableAllHeaderCode = 1
      additionalHeaders = Content-type:application/json
      xhtml_cleaning = 0
      debug = 0
      no_cache = 1
      admPanel = 0
   }
}

也许这个答案会让您得到想要的结果