【问题标题】:Magento 2 admin AJAX route not workingMagento 2 管理员 AJAX 路由不起作用
【发布时间】:2017-11-24 18:06:15
【问题描述】:

我正在尝试通过 Magento 2 管理区域中的 AJAX 访问 URL。我尝试了很多东西,但每次响应都是 404 Forbidden。

Firefox 的控制台显示如下:

这是我的模块的代码:

供应商/模块/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0">
    </module>
</config>

供应商/模块/etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="adminhtml">
            <module name="Vendor_Module" before="Magento_Backend" />
        </route>
    </router>
</config>

使用原型的 AJAX JS 代码:

new Ajax.Request('<?php /* @escapeNotVerified */ echo $block->getAdminUrl(); ?>adminhtml/action/add', {
    method: 'post',
    parameters: {'order_id' : <?php /* @escapeNotVerified */ echo $block->getOrderId(); ?>},
    onSuccess: function(response) {
        console.log($response);
        this.add();
    }.bind(this)
});

供应商/模块/控制器/Adminhtml/Action/Add.php

<?php
namespace Vendor\Module\Controller\Adminhtml\Action;

class Add extends \Magento\Backend\App\Action
{
    protected $_context;
    protected $_pageFactory;
    protected $_jsonEncoder;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Json\EncoderInterface $encoder,
        \Magento\Framework\View\Result\PageFactory $pageFactory
    ) {
        $this->_context = $context;
        $this->_pageFactory = $pageFactory;
        $this->_jsonEncoder = $encoder;
        parent::__construct($context);
    }

    public function execute()
    {
        $response = array('status' => 'success');
        $this->getResponse()->representJson($this->_jsonEncoder->encode($response));
        return;
    }
}

请告诉我如何通过 AJAX 访问此管理 URL。

【问题讨论】:

  • 404 禁止?这很奇怪。 404 通常表示未找到。 Forbidden 的状态码应该是 403。有些东西没有正确配置,虽然我不认为是你在这里显示的代码导致了它。
  • @Shahid 有什么解决办法吗?

标签: php ajax magento2


【解决方案1】:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="adminhtml" frontName="xyz">
            <module name="Vendor_Module" before="Magento_Backend" />
        </route>
    </router>
</config>

我确信路由配置文件中缺少 frontName 是弹出错误 404 的原因,因此请用上面指定的 frontName 替换 xyz

【讨论】:

    【解决方案2】:

    我已经尝试了上述所有方法,但没有一个有效或不完整,所以我决定详细回答: 以下是模块最小图

    1)

    <?xml version="1.0" ?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
        <router id="admin">
            <route frontName="groupproduct" id="groupproduct">
                <module before="Magento_Backend" name="Textmimedia_Partpicker"/>
            </route>
        </router>
    </config>
    

    2)

    <?xml version="1.0" ?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Levosoft_Partpicker" setup_version="1.0.0"/>
    </config>
    

    3) 需要声明管理路由器

        <?xml version="1.0" ?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
        <router id="admin">
            <route frontName="groupproduct" id="groupproduct">
                <module before="Magento_Backend" name="Levosoft_Partpicker"/>
            </route>
        </router>
    </config>
    

    4)

    <?php
    
    
    namespace Levosoft\Partpicker\Controller\Adminhtml\Imagetag;
    
    /**
     * Class Save
     *
     * @package Levosoft\Partpicker\Controller\Adminhtml\Imagetag
     */
    class Save extends \Magento\Backend\App\Action
    {
    
        protected $resultPageFactory;
        protected $jsonHelper;
    
        /**
         * Constructor
         *
         * @param \Magento\Backend\App\Action\Context  $context
         * @param \Magento\Framework\Json\Helper\Data $jsonHelper
         */
        public function __construct(
            \Magento\Backend\App\Action\Context $context,
            \Magento\Framework\View\Result\PageFactory $resultPageFactory,
            \Magento\Framework\Json\Helper\Data $jsonHelper,
            \Psr\Log\LoggerInterface $logger
        ) {
            $this->resultPageFactory = $resultPageFactory;
            $this->jsonHelper = $jsonHelper;
            $this->logger = $logger;
            parent::__construct($context);
        }
    
        /**
         * Execute view action
         *
         * @return \Magento\Framework\Controller\ResultInterface
         */
        public function execute()
        {
            try {
                return $this->jsonResponse('your response');
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                return $this->jsonResponse($e->getMessage());
            } catch (\Exception $e) {
                $this->logger->critical($e);
                return $this->jsonResponse($e->getMessage());
            }
        }
    
        /**
         * Create json response
         *
         * @return \Magento\Framework\Controller\ResultInterface
         */
        public function jsonResponse($response = '')
        {
            return $this->getResponse()->representJson(
                $this->jsonHelper->jsonEncode($response)
            );
        }
    }
    

    现在客户端部分实际上有点棘手,我在 js 文件中调用它,比如 somefilename.js

    var ajaxRequest;
                    var saveUrl = gpImageTagSaveUrl+'?isAjax=true'; //module url declared globally in module;
    
                    ajaxRequest = $.ajax({
                        showLoader: true,
                        url: saveUrl,
                        data: {form_key: window.FORM_KEY},
                        type: 'POST',
                        dataType: 'json',
                        beforeSend: function () {
                            $('#loader').show();
                        }
                    });
                    //Show successfully for submit message
                    ajaxRequest.done(function (response, textStatus, jqXHR) {
                        $("#ajaxResponse").html(response);
                        $('#loader').hide();
                    });
    
                    //On failure of request this function will be called
                    ajaxRequest.fail(function () {
                        //show error
                        $("#ajaxResponse").html('Oops, An error occured, please' +
                            ' try again later!');
                        $('#loader').hide();
                    });
    

    gpImageTagSaveUrl 是全局变量,它将保存您的模块 url,您可以在一些 js 文件中声明它,如下所示

    我使用了 catalog_product_edit.xml 文件,因为我希望它位于产品编辑位置,您可以将其添加到所需的文件中,如果需要,可以添加到 default.xml 中。

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="js">
                <block class="Magento\Backend\Block\Template" template="Textmimedia_Partpicker::js.phtml"
                       name="custom_js_backend"/>
            </referenceContainer>
        </body>
    </page>
    

    现在在 js.phtml 中声明操作 url,如下所示:

    <script>
        require([
            "prototype"
        ], function () {
            window.gpImageTagSaveUrl = '<?= /** @noEscape */ $block->getUrl('groupproduct/imagetag/save')?>';
        });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 2012-10-07
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 2018-01-06
      相关资源
      最近更新 更多