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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38220376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:09:56  来源:igfitidea点击:

How I get ajax response from controller in magento 2

jqueryajaxmagento2

提问by ARVIND KARKAR

I try to make an ajax call and pass the dropdown value in controller and get that particular related order information in view file. Response comes true but how to utilize that response in my view file.

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

Here is my phtml file:

这是我的 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>

And here is my controller:

这是我的控制器:

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);
    }
}

回答by Ekta Puri

below is the example how to do this, Please modify it according to your requirement.

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

I used js template for this.

我为此使用了 js 模板。

Following example will create dropdown in your phtml file. you can use same method to display your data in the format you want.

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

In your JS

在你的 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;
    });

In Controller

在控制器中

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);
        }
    }

IN your phtml file

在你的 phtml 文件中

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

Hope that helps.

希望有帮助。