magento中的AJAX示例

时间:2015-08-16 06:01:37

标签: ajax magento-1.9

大家好,

我是Magento的新手。我想在Magento学习** ajax过程。**有没有人可以用一个简单的例子帮助我理解Magento中的ajax? 我们将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我给你一个简单的例子。要在Magento中使用基本的jQuery Ajax,您可以在phtml页面和Controller中工作。 只需在phtml页面中添加脚本:

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery(".like-result").click(function() {
            //alert(this.id);
            var id = this.id;
            //alert(custid);
            jQuery(".notify-status").hide();
            jQuery(".notify-loader").show();
            jQuery.ajax({      
            type: "POST",
            data: 'pid=' + id,
            url:'http://192.168.2.3/subhranil-demo/blog/index/likecount',
            success:function(response){                       
                if (response) {
                    jQuery(".notify-loader").hide();
                    jQuery(".notify-status").show();
                    jQuery("#un"+id).html(response);
                }
            }
            });
        });
     });
</script>

在jQuery.ajax下的上述脚本中,您还可以看到type,data,url。 type用于POST或GET等发送过程;在数据中,您将向控制器发送信息;在URL中,您可以声明控制器路径。这里我有一个'博客'模块,我在'index'控制器下编写公共函数,并给出函数名'likecount'。此外,我的基本路径是http://192.168.2.3/subhranil-demo/。所以我将链接添加到URL,如下所示:http://192.168.2.3/subhranil-demo/blog/index/likecount。 现在我转到我的控制器博客模块文件夹中的'IndexController.php'并打开它。在课程下我添加以下功能:

public function likecountAction()
    {
    $blogload = Mage::getModel('blog/blog')->load($_POST['pid']);
    $newid = $blogload['like']+1;
    $data = array('like'=> $newid);
    $blogload->addData($data);
    try {
        $blogload->setId($_POST['pid'])->save();
        echo $newid;

    } catch (Exception $e){
        echo $e->getMessage(); 
    }
    }

在博客数据库中,我有像pid(作为主键)之类的字段。当你点击'like-result'类时,这个函数就像那样增加+1。 我的div结构也是这样的:

<?php

    $allCollection=Mage::getModel("blog/blog")->getCollection();
    $allCollection->addFieldToFilter('status',1);
    if ($allCollection->count() >= 1)
    {
        $news = array();
        ?>
        <div class="blog clearfix">
        <?php
        foreach ($allCollection as $news)
        {?>   
<p class="like-result" id="<?php echo $news->getId(); ?>"> <?php echo $news->getLike(); ?> </p>
    <a style="display: none;" class="notify-loader"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/notify-loader.gif"></a>
    <a style="display: none;" class="notify-status"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/ststus.png"></a>
  <?php } ?>
        </div>
<?php } ?>

试试这个!