功能介紹:在Magento前臺表單中使用Ajax,表單輸入信息驗證經過,表單便可提交,驗證不經過,表單就不能提交。
前臺phtml模板頁面部分代碼以下:php
<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文件:html
<reference name="head"> <action method="addItem"><type>skin_js</type><name>js/count.js</name></action> </reference>
接下來,就須要寫count.js文件:
目錄爲:ajax
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中,frontend
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類能夠用。async