【问题标题】:PageController can't be requested via XmlHttpRequest in Shopware 6无法通过 Shopware 6 中的 XmlHttpRequest 请求 PageController
【发布时间】:2020-10-14 20:28:46
【问题描述】:

我正在尝试在最新的 Shopware 6.2.2 上向我的自定义 StorefrontController 发送请求,但我收到以下错误:

PageController can't be requested via XmlHttpRequest.

我正在做一个来自自定义 JS 插件的常规 httpClient 请求:


export default class MyCustomPlugin extends Plugin {

  static options = {
      dataUrl: '', // comes from the twig as "path('frontend.path.to.route')"
      product: null,
      params: {},
      loadingIndicatorClass: 'is-loading',
      responseSelector: 'some-selector-class'

  }

  init () {
      // this.el.innerHTML = LoadingIndicator.getTemplate()
      this.httpClient = new HttpClient()
      const query = querystring.stringify(this.options.product)
      this.sendDataRequest(query)
  }

  /**
   * Add classes to add loading styling.
   * Prevents the user from clicking filter labels during filter request.
   */
  addLoadingIndicatorClass () {
      this.el.classList.add(this.options.loadingIndicatorClass)
  }

  /**
   * Remove loading styling classes.
   */
  removeLoadingIndicatorClass () {
      this.el.classList.remove(this.options.loadingIndicatorClass)
  }

  /**
   * Send request to get filtered product data.
   *
   * @param {String} filterParams - active filters as querystring
   */
  sendDataRequest (filterParams) {

      this.addLoadingIndicatorClass()

      this.httpClient.abort()
      this.httpClient.get(`${this.options.dataUrl}?${filterParams}`, (response) => {
          this.renderResponse(response)
          this.removeLoadingIndicatorClass()
      })
  }

  /**
   * Inject the HTML of the response to the element.
   *
   * @param {String} response - HTML response
   */
  renderResponse (response) {
      ElementReplaceHelper.replaceFromMarkup(response, this.options.responseSelector, false)
      window.PluginManager.initializePlugins()
  }
}

这是我的StorefrontController 路线:

    /**
     * @Route("/path/to_route", name="frontend.path.to.route", methods={"GET"})
     */
    public function someAction(Request $request, Context $context): JsonResponse

谁能告诉我为什么请求没有进行?我想在 Shopware 6 中向我自己的控制器发送一个简单的 AJAX 请求。

谢谢!

【问题讨论】:

    标签: javascript ajax symfony shopware symfony-routing


    【解决方案1】:

    尝试添加:

    defaults={"XmlHttpRequest"=true} 到您的路线。

    所以在更改之后您将拥有:

    /**
    * @Route("/path/to_route", name="frontend.path.to.route", methods={"GET"}, defaults={"XmlHttpRequest"=true})
    */
    

    还要确保使用 @RouteScope 注释在控制器中正确定义范围。由于您的代码是店面 JavaScript 插件,因此应定义 storefront 范围。

    【讨论】:

      猜你喜欢
      • 2011-12-23
      • 2015-05-03
      • 2020-12-16
      • 2016-02-26
      • 2020-12-04
      • 1970-01-01
      • 2015-03-10
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多