Magento 2:如何使用自定义格式的Ajax格式发送数据?


11

谁能解释我如何在Magento-2页面上创建一个简单表单以使用Ajax发送数据?我已经有一个表单和控制器操作,可以不使用ajax发送数据。


我认为此链接将帮助您单击此处
Pankaj Sharma

看看我的回答,它会比被接受的问题帮助更多
LucScu

显示响应错误>未定义的属性:> namespace \ modulename \ Controller \ Index \ Index \ Interceptor :: $ _ jsonHelper请分享以改善答案
Rohit Chauhan

Answers:


15

您只需在phtml文件中设置以下代码以使用ajax,就必须在以下代码中更改customurl

<script type="text/javascript">
    require(["jquery"],function($) {
        $(document).ready(function() {
            var customurl = "<?php echo $this->getUrl().'frontname/index/index'?>";
            $.ajax({
                url: customurl,
                type: 'POST',
                dataType: 'json',
                data: {
                    customdata1: 'test1',
                    customdata2: 'test2',
                },
            complete: function(response) {             
                country = response.responseJSON.default_country;
                state = response.responseJSON.state;         
                console.log(state+' '+country);   
                },
                error: function (xhr, status, errorThrown) {
                    console.log('Error happens. Try again.');
                }
            });
        });
    });
</script>

在控制器文件中的execute()方法中,

<?php
 use Magento\Framework\Controller\ResultFactory;
 public function execute()
    {
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

        $response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $response->setHeader('Content-type', 'text/plain');
        $country = 'india';
        $state = 'gujarat';
        $response->setContents(
            $this->_jsonHelper->jsonEncode(
                [
                    'default_country' => $country,
                    'state' => $state,
                ]
            )
        );
        return $response;
    } 

4
您可以使用$ this-> getRequest()-> getParam('customdata1')在控制器中获取数据;
Rakesh Jesadiya

1
响应正在脚本响应中。
Rakesh Jesadiya

2
完成:功能(响应)在这里您已经得到响应。
Rakesh Jesadiya

1
您必须在控制器中的$ this-> _ jsonHelper-> jsonEncode(['default_country'=> $ country,'state'=> $ state,])代码上方设置响应
Rakesh Jesadiya

1
在上述情况下,default_country和state是响应的返回结果
Rakesh Jesadiya

13

接受的答案是好的,但是我认为利用magento core提供的js验证可能会有用。因此,尝试使用以下js脚本:

<script type="text/javascript">
require([
    "jquery",
    "mage/mage"
],function($) {
    $(document).ready(function() {
        $('#form_id').mage(
            'validation',
            { 
                submitHandler: function(form) {
                    $.ajax({
                        url: "url to module/controller/action",
                        data: $('#form_id').serialize(),
                        type: 'POST',
                        dataType: 'json',
                        beforeSend: function() {
                            // show some loading icon
                        },
                        success: function(data, status, xhr) {
                            // data contains your controller response
                        },
                        error: function (xhr, status, errorThrown) {
                            console.log('Error happens. Try again.');
                            console.log(errorThrown);
                        }
                    });
                }
            }
        );
    });
});
</script>

不要忘记控制器必须返回JSON响应,例如:

$response = $this->resultFactory
    ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
    ->setData([
        'status'  => "ok",
        'message' => "form submitted correctly"
    ]);

return $response;

1
比接受的答案更好的解决方案。谢谢男人
麦地那
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.