如何将Ajax发布请求发送到前端控制器(AdressController.php)

时间:2019-04-16 11:52:35

标签: ajax prestashop-1.6

我有一个select下拉列表,当我从该下拉列表中选择一个值时,我正尝试从address.tpl发送一个ajax发布请求到AddressController.php。

我似乎找不到如何将表单发送到正确的URL(控制器的url,其路径为:/public_html/override/controllers/front/AddressController.php)

我的ajax请求位于address.tpl

<script>
    {literal}

        var uriAddress = 'index.php?controller=AddressController&action=example&token=922fb5c427f8abfa1eaf7aa175c9529b';



        $('#id_state').change( function() {
           $(this).find(":selected").each(function () {                              
                city = $(this).text();                   
            });

            $.ajax({
                url : uriAddress,
                type : 'POST',
                async: true,
                cache: false,
                dataType : "json",
                data: {
                    city: city
                },
                success : function (result) {
                    console.log(result);
                }
            });
        });

    {/literal}
</script>

这是我的AddressController.php

    public function displayAjax()
    {
        if (count($this->errors))
        {
            $return = array(
                'hasError' => !empty($this->errors),
                'errors' => $this->errors
            );
            die(Tools::jsonEncode($return));
        }

        if(Tools::getValue('MyControllerAction')=='myMyControllerAction')
        {
            $cities = array();
            $sql = 'SELECT judet, localitate FROM sdn_fancourier_cities WHERE judet = "alba"';
            if ($results = Db::getInstance()->ExecuteS($sql))
            foreach ($results as $resultCity) {
                array_push($cities, $resultCity);
            }

            $this->context->smarty->assign(array(
                'city_list' => $cities,     
            ));

           return json_encode($this->context->smarty->assign(array(
                'city_list' => $cities,     
            )));

        }

    }

1 个答案:

答案 0 :(得分:0)

仅当您在displayAjax()调用中发送ajax参数时,才会调用$.ajax函数。

此外,当您发送action参数(在您的情况下为“示例”)时,调用的函数将为displayAjaxExample()

您的AddressController.php应该是这样的:

class AddressController extends AddressControllerCore
{
    public function displayAjaxExample()
    {
        [YOUR CODE HERE]
    }
}

,您的ajax调用应为:

$.ajax({
    url : uriAddress,
    type : 'POST',
    async: true,
    cache: false,
    dataType : "json",
    data: {
        city: city,
        ajax: 1
    },
    success : function (result) {
        console.log(result);
    }
});