如何从 magento 2 中的控制器获取 ajax 响应

问题描述 投票:0回答:1

我尝试进行ajax调用并在控制器中传递下拉值,并在视图文件中获取特定的相关订单信息。响应成立,但如何在我的视图文件中利用该响应。

这是我的phtml文件

<select id="chartOption">
   <option value="">Select Option</option>
   <option value="status">Status</option>
   <option value="payments">Payments</option>
   <option value="browser">Browser</option>
</select>
<input type="button" name="chart_button" value="Generate chart" onclick="click_chart()">
<div id="result"></div>
<script type="text/javascript">
        function click_chart() {
            var a = document.getElementById("chartOption");
            var abc = a.options[a.selectedIndex].value;
            data = jQuery(this).serialize();
            jQuery.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: "Blog/Post/Information", 
                data: "label=" + abc,
                success: function (result) { jQuery('#result').html(result); },
                error: function (error) {  jQuery('#result').html(error); }
            });
        }
</script>

这是我的控制器:

public function execute() {
    if (isset($_REQUEST['ajax'])) {
        $label = $this->getRequest()->getPost('label');
        $_orders = $this->getOrders();
        $complete = $pending = $closed = $canceled = $processing = $onHold = 0;
        foreach ($_orders as $_order):
            $label = $_order->getStatusLabel();
            if ($label == 'Complete') {
                $complete++;
            }
            if ($label == 'Pending') {
                $pending++;
            }
            if ($label == 'Closed') {
                $closed++;
            }
            if ($label == 'Canceled') {
                $canceled++;
            }
            if ($label == 'Processing') {
                $processing++;
            }
            if ($label == 'On Hold') {
                $onHold++;
            }
        endforeach;
        $orderData = "['Task', 'Hours per Day'],['Complete'," . $complete . "],['Pending'," . $pending . "]],['Processing'," . $processing . "]],['Canceled'," . $canceled . "]";
        $arr = array('result' => $orderData);
        $jsonData = json_encode(array($arr));
        $this->getResponse()->setHeader('Content-type', 'application/json');
        $this->getResponse()->setBody($jsonData);
    }
}
jquery ajax magento2
1个回答
7
投票

以下是如何执行此操作的示例,请根据您的要求进行修改。

我为此使用了js模板。

以下示例将在您的 phtml 文件中创建下拉菜单。您可以使用相同的方法以您想要的格式显示数据。

在你的JS中

define([
        'jquery',
        'underscore',
        'mage/template',
        'jquery/list-filter'
        ], function (
            $,
            _,
            template
        ) {
            function main(config, element) {
                var $element = $(element);
                $(document).on('click','yourID_Or_Class',function() {
                        var param = 'ajax=1';
                            $.ajax({
                                showLoader: true,
                                url: YOUR_URL_HERE,
                                data: param,
                                type: "POST",
                                dataType: 'json'
                            }).done(function (data) {
                                $('#test').removeClass('hideme');
                                var html = template('#test', {posts:data}); 
                                $('#test').html(html);
                            });
                    });
            };
        return main;
    });

在控制器中

public function __construct(
        Context                                             $context,
        \Magento\Framework\Controller\Result\JsonFactory    $resultJsonFactory,
    ) {
        
        $this->resultJsonFactory            = $resultJsonFactory;
        parent::__construct($context);
    }


    public function execute()
    {
        $result                 = $this->resultJsonFactory->create();
        if ($this->getRequest()->isAjax()) 
        {
            $test=Array
            (
                'Firstname' => 'What is your firstname',
                'Email' => 'What is your emailId',
                'Lastname' => 'What is your lastname',
                'Country' => 'Your Country'
            );
            return $result->setData($test);
        }
    }

在你的 phtml 文件中

<style>  
.hideme{display:none;}
</style>
<div id='test' class="hideme">
    <select>
    <% _.each(posts, function(text,value) { %>
        <option value="<%= value %>"><%= text %></option>
    <% }) %> 
    </select>
</div>

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.