我需要进行AJAX调用以覆盖Front Controller。我尝试过的最后一种方法是返回403
状态代码,但在responseText
中它会显示正确的JSON。
如何协调并修复它以便正确返回200 OK
以及正确的JSON?
<?php
class CategoryController extends CategoryControllerCore{
public function init()
{
parent::init();
// check if URL contain ajax option and set it.
if( $this->ajax = Tools::getValue( "ajax" ) ){
if( $this->ajax ){
$action = Tools::getValue( 'action' );
if( !empty( $action ) && method_exists( $this, 'ajaxProcess' . Tools::toCamelCase( $action ) ) ){
// Return the method call
$this->{'ajaxProcess' . Tools::toCamelCase( $action )}();
} else {
$this->AjaxProcess();
}
// Required to avoid errorHandler in AJAX
exit;
}
}
}
public function ajaxProcessMyAjaxMethod()
{
$customerId = Tools::getValue( 'customerId' );
print Tools::jsonEncode( array(
'customerId' => $customerId,
'msg' => 'Hello PS AJAX!!!',
) );
}
}
这是我的JavaScript代码:
$.ajax({
url: baseUri + 'index.php',
type: 'GET',
cache: true,
dataType: 'json',
data: {
controller: 'Category',
action: 'MyAjaxMethod',
customerId: 45,
ajax: 1,
token: token
},
})
.done(function (data, textStatus, jqXHR) {
console.log(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(jqXHR.responseText);
});
答案 0 :(得分:1)
CategoryController
必须id_category
才能成功投放。你可以在那里添加:
...
data: {
controller: 'Category', /* better lowercase 'category' */
id_category: 3, /* your ID category */
action: 'MyAjaxMethod', /* if you are using 'toCamelCase', it can be 'my_ajax_method' */
customerId: 45,
ajax: 1,
token: token
}
...
请确保您将其传递到正确的网址(因此url: baseUri + 'index.php'
是正确的。)