多个Ajax形式,带有jQuery形式



当前,我正在使用jQuery表单插件来通过.ajaxForm({});在Magento产品列表上处理多个Ajax表单。现在,我正在使用的解决方案,但是它是超级笨拙的,很想知道是否有更好的方法来解决此问题。

我会为简短缩短代码:

<?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进行此操作,该内置的每 foreach()循环(即:derp-1,derp-2,derp-3)增加,并为每种表单添加一个增量ID。

我知道我可以使用类选择器来定位每种形式,例如jQuery('.derp').ajaxForm({});,但是我仍然需要能够将其与VarienForm相关联。

我试图基于提交按钮.each( function({ jQuery(this).on('click', function({ //AJAX STUFF HERE }) ); }) );的即时生成ajaxForm({});,但这不起作用。

是否有一个更强大的解决方案可以独立针对每种形式,生成VarienForm,抓住我需要的任何形式的数据,利用ajaxForm({})方法并将其保持在一起?

我将创建一个您在页面上声明一次的函数。通过在每个PHP循环迭代中调用它,通过传递一些特定于迭代的参数来使用它(正如您指出的那样,许多JavaScript已重复)。例如,该函数可能是:

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

并替换只有iterator的JavaScript串联打印迭代器的PHP代码的每个实例。

您将用这样的东西替换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);
            });
        }
    });
}

主要查看评论,以查看我在哪里更改您的实际代码。

最新更新