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

时间:2016-07-06 09:17:04

标签: jquery ajax magento2

我尝试进行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);
    }
}

1 个答案:

答案 0 :(得分: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>

希望有所帮助。