簡體   English   中英

帶有jQuery Form的多個AJAX表單

[英]Multiple AJAX forms with jQuery Form

目前,我正在使用jQuery Form插件通過.ajaxForm({});處理Magento產品列表上的多個AJAX表單.ajaxForm({}); 現在,我正在使用的解決方案可行,但是它非常笨拙,很想知道是否有更好的方法來解決此問題。

為了簡潔起見,我將代碼縮短一些:

<?php foreach ($_productCollection as $_product): ?>
<form action="<?php echo $this->getSubmitUrl($_product) ?>" method="post" class="derp" id="derp-<?php echo $_iterator; ?>">
    <div class="quanitybox">
        <label for="qty"><?php echo $this->__('Quantity:') ?></label>
        <input type="button" class="quantity_box_button_down" />         
        <input type="text" name="qty" maxlength="12" value="1" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
        <input type="button" class="quantity_box_button_up" />
    </div>
    <button type="submit" title="Add to Cart" class="button btn-cart" ><span><span>Add to Cart</span></span></button>
 </form>

 <script type="text/javascript">
    var productAddToCartForm = new VarienForm('derp-<?php echo $_iterator ?>');

    jQuery('#derp-<?php echo $_iterator ?>').ajaxForm({
                url: jQuery('#derp-<?php echo $_iterator ?>').attr('action').replace("checkout/cart","ajax/index"),
                data: {'isAjax':1},
                dataType: 'json',
                beforeSubmit: function(){    
                    if(productAddToCartForm.validator.validate()){
                        windowOver.show();
                        windowBox.show().css({
                            backgroundImage: "url('<?php echo $this->getSkinUrl('images/loading.gif')?>')"
                        });                    
                    }else{
                        return false;
                    }
                },
                error: function(data){
                    windowBox.css({
                          backgroundImage: 'none'
                    }).html('<?php echo $this->__('Error') ?>');                       
                    windowOver.one('click',function(){
                        hidewindow(windowBox,windowOver);                    
                    });        

                    jQuery('#hidewindow').click(function(){
                        hidewindow(windowBox,windowOver);                    
                    });
                },
                success : function(data,statusText,xhr ){
                    if(data.status == 'SUCCESS'){
                        if(jQuery('.block-cart')){
                            jQuery('.block-cart').replaceWith(data.sidebar);
                        }
                        if(jQuery('.header .block-cart-header')){
                            jQuery('.header .block-cart-header').replaceWith(data.topcart);
                        }     
                        msgHtml = '<div class="added-content"><div style="float:left;">' + productImg + '</div><em>' + titleForBox<?php echo $_iterator ?> + '</em> <?php echo $this->__('was successfully added to your shopping cart.') ?><div style="clear:both;"></div><a id="hidewindow" href="javascript:void(0);"><?php echo $this->__('Continue shopping') ?></a>&nbsp;<a href="<?php echo $this->getUrl('checkout/cart')?>"><?php echo $this->__('View cart & checkout') ?></a></div>';             
                    }else{
                        msgHtml = '<div class="added-content"><p class="error-msg" style="margin-bottom:15px;">' + data.message + '</p><a id="hidewindow" href="javascript:void(0);"><?php echo $this->__('Continue shopping') ?></a>&nbsp;<a href="<?php echo $this->getUrl('checkout/cart')?>"><?php echo $this->__('View cart & checkout') ?></a></div>';
                    }                      

                    windowBox.css({
                          backgroundImage: 'none'
                    }).html(msgHtml);                      
                    windowOver.one('click',function(){
                        hidewindow(windowBox,windowOver);                    
                    });        

                    jQuery('#hidewindow').click(function(){
                        hidewindow(windowBox,windowOver);                    
                    });    
                }
            });
</script>
<?php endforeach; ?>

這段代碼的不幸部分是我在每個產品的底部生成了一堆重復的JavasScript。

我真的沒有辦法解決這個問題,因為我需要為每個產品生成一個new VarienForm()進行驗證,該驗證只需要一個表單ID(除非我弄錯了)。

我正在使用內置的$_iterator進行此操作,該$_iterator每個foreach()循環遞增(即derp-1,derp-2,derp-3),並為每種形式添加一個遞增的id。

我知道我可以使用類選擇器來定位每種表單,例如jQuery('.derp').ajaxForm({}); 但是,我仍然需要能夠將其關聯到VarienForm

我試圖生成ajaxForm({}); 基於提交按鈕.each( function({ jQuery(this).on('click', function({ //AJAX STUFF HERE }) ); }) ); 但這沒有用。

是否有更健壯的解決方案可獨立針對每種表單,生成VarienForm ,獲取我需要的任何表單數據,利用ajaxForm({})方法並將其全部保存在一起?

我將創建一個在頁面上一次聲明的函數。 通過在每次PHP循環迭代中調用它,並傳遞一些特定於該迭代的參數,可以使用它(如您所指出的,很多Javascript是重復的)。 例如,函數可以是:

function setupForm(form, iterator) {
    jQuery("#derp-" + iterator).ajaxForm({

    });
}

而取代你的PHP代碼的每個實例,打印與一個只有一個Javascript級聯迭代器iterator

您可以將PHP循環中的腳本替換為以下內容:

var productAddToCartForm = new VarienForm('derp-<?php echo $_iterator ?>');
setupForm(productAddToCartForm, '<?php echo $_iterator ?>');

當然,您必須向循環專用的setupForm函數添加更多參數(我將仔細閱讀代碼以嘗試確定它們的全部內容)。 這樣,您可以使所有PHP循環項僅打印一次(在setupForm函數調用中),並在setupForm函數內部動態使用它們。

UDPATE

我仔細研究了一下,希望找到了需要替換的所有內容,因此我將在這段簡短的內容之后粘貼代碼。 我擔心的是這些變量是什么:

windowBox
windowOver
productImg
titleForBox

如果它們是全局的,則此新更新應該很好。 如果它們處於某種其他環境中(某種程度上),那么這可能不起作用。

無論如何,這是我認為最終可能會這樣的情況:

// Use this in your PHP loop
var productAddToCartForm = new VarienForm('derp-<?php echo $_iterator ?>');
setupForm(productAddToCartForm, "<?php echo $_iterator ?>", "<?php echo $this->getSkinUrl('images/loading.gif')?>", "<?php echo $this->__('Error') ?>", "<?php echo $this->__('was successfully added to your shopping cart.') ?>", "<?php echo $this->__('Continue shopping') ?>", "<?php echo $this->getUrl('checkout/cart')?>", "<?php echo $this->__('View cart & checkout') ?>");

// Use this one time in your page
function setupForm(form, iterator, skin_url, an_error, successful_text, continue_text, checkout_url, checkout_text) {
    var the_form = jQuery("#derp-"+iterator);  // Added this (obviously)

    the_form.ajaxForm({  // Changed this line
        url: the_form.attr('action').replace("checkout/cart","ajax/index"),  // Changed this line
        data: {'isAjax':1},
        dataType: 'json',
        beforeSubmit: function(){    
            if(form.validator.validate()){  // Changed this line
                windowOver.show();
                windowBox.show().css({
                    backgroundImage: "url('" + skin_url + "')"  // Changed this line
                });                    
            }else{
                return false;
            }
        },
        error: function(data){
            windowBox.css({
                  backgroundImage: 'none'
            }).html(an_error);  // Changed this line

            windowOver.one('click',function(){
                hidewindow(windowBox,windowOver);
            });

            jQuery('#hidewindow').click(function(){
                hidewindow(windowBox,windowOver);                    
            });
        },
        success : function(data,statusText,xhr){
            var msgHtml = "";  // Added this line
            if(data.status == 'SUCCESS'){
                if(jQuery('.block-cart')){
                    jQuery('.block-cart').replaceWith(data.sidebar);
                }
                if(jQuery('.header .block-cart-header')){
                    jQuery('.header .block-cart-header').replaceWith(data.topcart);
                }
                msgHtml = '<div class="added-content"><div style="float:left;">' + productImg + '</div><em>' + titleForBox + iterator + '</em> ' + successful_text + '<div style="clear:both;"></div><a id="hidewindow" href="javascript:void(0);">' + continue_text + '</a>&nbsp;<a href="' + checkout_url + '">' + checkout_text + '</a></div>';  // Changed this line
            }else{
                msgHtml = '<div class="added-content"><p class="error-msg" style="margin-bottom:15px;">' + data.message + '</p><a id="hidewindow" href="javascript:void(0);"><?php echo $this->__('Continue shopping') ?></a>&nbsp;<a href="' + checkout_url + '">' + checkout_text + '</a></div>';  // Changed this line
            }

            windowBox.css({
                  backgroundImage: 'none'
            }).html(msgHtml);
            windowOver.one('click',function(){
                hidewindow(windowBox,windowOver);
            });

            jQuery('#hidewindow').click(function(){
                hidewindow(windowBox,windowOver);
            });
        }
    });
}

主要查看注釋,看看我在哪里更改了您的實際代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM