从Prestashop模块发出ajax请求

时间:2017-04-29 13:59:16

标签: prestashop prestashop-1.7

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

谢谢!

1 个答案:

答案 0 :(得分:8)

这很简单,您只需要使用Prestashop标准制作控制器,然后将其链接到您的前端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');

    }
}

?>

在您的模块挂钩中,您需要访问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准备使用控制器