如何在Magento 2.1.0中进行简单的Ajax调用


11

我在一个phtml文件中添加了一个简单的按钮。

<input type='button' name='emq_zip_btn' class='emq_zip_btn' value='Go'>

我从自定义模块(Ved_Mymodule)添加了一个自定义js文件(“ emq.js”):

require([
    "jquery",
    "jquery/ui"
], function($v){
//<![CDATA[
    $v = jQuery.noConflict();
    $v(document).ready(function() 
    {
        console.log('jquery loaded from emq.js');
        $v(".emq_zip_btn").on('click',function(e)
        {
            console.log('clicked');
        });
    });
//]]>
});

当我单击以上按钮时,控制台中将打印“ clicked”,即jQuery正常工作。

这是来自自定义模块Ved_Mymodule的控制器文件:

Ved \ Mymodule \ Controller \ Index \ Index.php:

<?php

namespace Ved\Mymodule\Controller\Index;

use Ved\Mymodule\Model\NewsFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
{
    /**
     * @var \Tutorial\SimpleNews\Model\NewsFactory
     */
    protected $_modelNewsFactory;

    /**
     * @param Context $context
     * @param NewsFactory $modelNewsFactory
     */
    public function __construct(
        Context $context,
        NewsFactory $modelNewsFactory
    ) {
        parent::__construct($context);
        $this->_modelNewsFactory = $modelNewsFactory;
    }

    public function execute()
    {

    }
}

Ved / Mymodule / etc / frontend / routes.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/
App/etc/routes.xsd">
    <router id="standard">
        <route id="news" frontName="news">
            <module name="Ved_Mymodule" />
        </route>
    </router>

我的问题是如何从此控制器方法返回数据,然后通过jQuery访问它,即单击该按钮后如何进行简单的Ajax调用。


vedu您能解释一下should我应该在产品详细信息页面上添加cuctom复选框吗?选中时,我想增加产品价格$ 0.50,并在购物车中更新至
— Ashwini

Answers:


19

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

我为此使用了js模板。

以下示例将使用ajax功能在您的phtml文件中创建下拉列表。

在你的JS里

define([
        'jquery',
        'underscore',
        'mage/template',
        'jquery/list-filter'
        ], function (
            $,
            _,
            template
        ) {
            function main(config, element) {
                var $element = $(element);
var YOUR_URL_HERE = config.AjaxUrl;
                $(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>
<script type="text/x-magento-init">
        {
            "*": {
                "[Namespace]_[Modulename]/js/YOURFILE": {
                    "AjaxUrl": "<?php echo $block->getAjaxUrl(); ?>",
                }
            }
        }
</script>
<div id='test' class="hideme">
    <select>
      <% _.each(posts, function(text,value) { %>
         <option value="<%= value %>"><%= text %></option>
      <% }) %> 
     </select>
</div>

getAjaxUrl应该在您的阻止文件中起作用,该阻止文件将返回URL

希望能有所帮助。


谢谢您的回答。您能告诉我在$ .ajax方法的url参数中应该提及什么吗?我的控制器的frontName是新闻。
— vedu

modulefrontname /索引/消息,如果你的控制器路径thsi将工作[命名空间] / [模块名] /Controller/Index/News.php我更喜欢通过从创建使用$这个- >从的getURL座网址模板文件的URL
— 的Ekta普里

是的,在magento 1中,我还仅从模板文件传递了url。但在magento 2模板文件中的jquery代码不起作用。
— vedu

我更新了答案,它在phtml文件中包含代码以加载js,但您的js应该在您的模块文件夹中
— Ekta Puri

您可以使用config.AjaxUrl
— Ekta Puri
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.