从 Prestashop 模块发出 ajax 请求

Make an ajax request from a Prestashop module

我正在制作一个模块,我需要发出 ajax 请求,如果可能,需要 JSON 响应,我该怎么做? 我不太了解 Prestashop 1.7 的结构。

谢谢!

这很简单,你只需要用 Prestashop 的标准制作控制器,然后 link 它到你的前端 Javascript。

像这样命名一个 php 文件:./modules/modulename/controllers/front/ajax.php

然后放入:

<?php

// Edit name and class according to your files, keep camelcase for class name.
require_once _PS_MODULE_DIR_.'modulename/modulename.php';

class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {

        $module = new ModuleName;

        // You may should do some security work here, like checking an hash from your module
        if (Tools::isSubmit('action')) {

            // Usefull vars derivated from getContext
            $context = Context::getContext();
            $cart = $context->cart;
            $cookie = $context->cookie;
            $customer = $context->customer;
            $id_lang = $cookie->id_lang;

            // Default response with translation from the module
            $response = array('status' => false, "message" => $module->l('Nothing here.'));

            switch (Tools::getValue('action')) {

                case 'action_name':

                    // Edit default response and do some work here
                    $response = array('status' => true, "message" => $module->l('It works !'));
                    
                    break;

                default:
                    break;

            }
        }

        // Classic json response
        $json = Tools::jsonEncode($response);
        echo $json;
        die;

        // For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
        // Just put some vars in your template
        // $this->context->smarty->assign(array('var1'=>'value1'));
        // $this->setTemplate('template.tpl');

        // For sending a template in ajax use this method
        // $this->context->smarty->fetch('template.tpl');

    }
}

?>

在你的Module Hooks中,你需要在JS中访问路由,所以我们基本上做一个变量:

// In your module PHP
public function hookFooter($params)
{
    
    // Create a link with the good path
    $link = new Link;
    $parameters = array("action" => "action_name");
    $ajax_link = $link->getModuleLink('modulename','controller', $parameters);

    Media::addJsDef(array(
        "ajax_link" => $ajax_link
    ));

}

在前端,您只需在 JS 文件中这样调用它(此处使用 jQuery):

// ajax_link has been set in hookfooter, this is the best way to do it
$(document).ready(function(){

    $.getJSON(ajax_link, {parameter1 : "value"}, function(data) {

        if(typeof data.status !== "undefined") {

            // Use your new datas here
            console.log(data);

        }

    });

});

瞧,你已经准备好 ajax 使用控制器