功能介绍:在Magento前台表单中使用Ajax,表单输入信息验证通过,表单即可提交,验证不通过,表单就不能提交。
前台phtml模板页面部分代码如下:

<form id="count" onsubmit="return checkForm()" action="<?php echo Mage::getUrl('count/index/save') ?>" method="post" >
    <input type="text" id="Serial_Number" name="Serial_Number" class="required-entry"/><span id="span"></span>
    <input type="submit" id="submit" value="<?php echo $this->__('submit') ?>"  />
</form>

布局文件中添加需要加载的js文件:

<reference name="head">
    <action method="addItem"><type>skin_js</type><name>js/count.js</name></action>
</reference>

接下来,就需要写count.js文件:
目录为:

skin/frontend/rwd/default/js/count.js

count.js内容为:

$j(document).ready(function(){
    $j("[name=Serial_Number]").blur(function(){
       var Serial_Number=$j("[name=Serial_Number]").val();
       //alert(Serial_Number);
       
    $j.ajax({
          type:"post",
          url:"/count/index/check",
          data:"Serial_Number="+Serial_Number,
          async:true,
          success:function(msg){
            $j("#span").html(msg);
          }
    });
    
    });
})

function checkForm() {
        //alert(123);
        //var Serial_Number = document.getElementById("Serial_Number");
        var span=document.getElementById("span");
        //alert(span);
        if (span.innerHTML == '序列号已存在' || span.innerHTML == '请输入正确的序列号')
        {
            //alert(span.innerHTML);
            return false;
        } else {
            // Submit Form When All values are valid.
            return true;
        }
    
}

写ajax的时候,会写到url地址,这里,我把处理页面卸载IndexController中,

    public function checkAction()
    {
        //接收参数
        $Serial_Number = $this->getRequest()->getParam('Serial_Number');

        //$model = Mage::getModel('count/count');     
        //查询数据库
        $read = Mage::getSingleton("core/resource")->getConnection('core_read');
        //$query="select count(*) from serial where serial_number='{$Serial_Number}'";
        $query = $read->select()->from('serial')->where('serial_number = ?', $Serial_Number);
        $result = $read->fetchOne($query); 
        if($result>0)
        {
            $read = Mage::getSingleton("core/resource")->getConnection('core_read');
            $res = $read->select()->from('count')->where('serial_number = ?', $Serial_Number);
            $row = $read->fetchOne($res);
            if($row>0)
            {
                echo "序列号已存在";
            }else{
                echo "序列号正确";
            }
        }else{
            echo "请输入正确的序列号";
        }
    }

到此,就完成了在magenot中加载自己写的ajax了。
备注:
magento也有默认的ajax类可以用。


denson
366 声望57 粉丝

引用和评论

0 条评论