只有在Prestashop生成模板文件時纔會在運行時執行掛鉤。在這裏你想在你的模塊中創建一個ajax函數。
你的模塊文件將是這樣的:
- mymodule.php
- ajax/
- my_module_ajax.php
- js/
- my_module.js
- views/
- templates/
- front/
- my_module_template.tpl
在文件mymodule.php
你已經有了:
<?php
if (!defined('_PS_VERSION_'))
exit;
class MyModule extends Module
{
public function __construct()
{
[...]
}
public function install()
{
if (!parent::install() || !$this->registerHook('header'))
return false;
return true;
}
public function hookHeader($params)
{
$this->context->controller->addJS(($this->_path).'js/my_module.js');
}
public function _ajax_create_product($params)
{
[...]
return $result;
}
}
在文件my_module_ajax.php
你已經有了:
<?php
require_once(dirname(__FILE__).'/../../../config/config.inc.php');
require_once(dirname(__FILE__).'/../../../init.php');
require_once(dirname(__FILE__).'/../mymodule.php');
$context = Context::getContext();
// Instance of module class
$module = new MyModule();
switch (Tools::getValue('action'))
{
case 'createProduct':
echo $module->_ajax_create_product(Tools::getValue('test'));
break;
default:
die('error');
}
在文件my_module.js
你有:
$(document).ready(function(){
$(document).on('click', '#myButton', function(){
createProduct('a_value');
});
});
function createProduct(value) {
$.ajax({
type: 'GET',
url: baseDir + 'modules/mymodule/ajax/my_module_ajax.php?rand=' + new Date().getTime(),
headers: { "cache-control": "no-cache" },
async: true,
cache: false,
data: 'action=createProduct&value=' + value+ '&other=' + 'test',
success: function(data)
{
console.log("product created");
}
});
}
在文件my_module_template.tpl
你已經有了:
<button id="myButton" name="myButton">Create product!</button>
此代碼是不是測試,應該可以適應您的需求,但整體的概念在這裏。
而不是調用掛鉤,你應該調用該方法來創建一個產品,它會爲你調用鉤子。 – TheDrot
@TheDrot:創建產品的方法是掛鉤功能。鉤子函數在php文件中。從php文件到tpl文件調用函數的唯一方法是使用鉤子。沒有? – androniennn
那麼你做錯了,因爲在創建產品後,鉤子將用於做一些額外的事情**。 – TheDrot