2016-12-22 85 views
0

我在Magento中创建了一个控制器,用于检查列表中是否有产品。如果列表中的产品将返回true,否则返回falsepreventDefault取决于Ajax响应的链接

这里是触发ajax调用的前端,我记住我无法将其改为表单。它必须是一个链接。

<a href="[my_controller]" title="Compare Products" target="_blank" class="compare-product-link">Compare Products</a> 

这是ajax调用。

jQuery(".compare-product-link").on("click", function(e) { 
    jQuery.ajax({ 
     async : false, 
     dataType : "json", 
     url  : "/compareextra/compare/allowed", 
     success : function(data) { 
      //console.log(data); 
      if(data.isAllowed != true) { 
       e.preventDefault(); 
      } 
     } 
    }); 
}); 

我的问题是,async已被弃用,不利于用户体验,他说,有很多答案在那里里面加3秒的延迟,我也不想这样,因为多数民众赞成对用户体验不利。

我也试过使用承诺电话,但它只能与async : false一起使用。

jQuery(".compare-product-link").on("click", function(e) { 
     var response = false; 
     jQuery.ajax({ 
      dataType : "json", 
      url  : "/compareextra/compare/allowed", 
      success : function(data) { 
       console.log(data); 
       if(data.isAllowed) { 
        response = true; 
       } 
      } 
     }).done(function(){ 
      console.log(response); 
      if(response != true) { 
       e.preventDefault(); 
      } 
     }); 
    }); 

编辑

还有一个问题我也有是,如果我的链接存储到一个变量,然后打开一个新的窗口,所以window.location = href;大多数浏览器会阻止其用户将必须手动接受弹出窗口目标网站,这再次不利于用户体验。

+0

一个常规的点击可能不是你的问题的根源,但我认为你是混合新旧形式的AJAX在.success()和.done()回调。在这个链接中有一个关于ajax/promises/deferreds的体面解释:http://tutorials.jenkov.com/jquery/deferred-objects.html。 –

回答

1

像你说的那样,由于异步,你无法真正实现这一点使用preventDefault。 什么,我会尝试是:

的preventDefault

href作为变量

调用AJAX

如果属实,而不是如有虚假

jQuery(".compare-product-link").on("click", function(e) { 
    var href = $(this).attr('href'); 
    e.preventDefault(); 
    jQuery.ajax({ 
     async : false, 
     dataType : "json", 
     url  : "/compareextra/compare/allowed", 
     success : function(data) { 
      //console.log(data); 
      if(data.isAllowed == true) { 
       window.location = href; 
      } 
     } 
    }); 
}); 

如果您重定向到href变量需要创建链接操作,您可以使用此代码:

function triggerClick(url){ 
    $('body').append('<span id="click_me_js"><a href="'+url+'"></a></span>'); 
    $('span#click_me_js a')[0].click(); 
    $('span#click_me_js').remove(); 
} 

这将模仿上<a>

+0

'window.location = href;',和preventDefault(),重新加载页面使得是不同的..我想。 – Vikrant

+0

请参阅我编辑的问题。 –

+0

@AndréFerraz,所以你想避免'async'调用延迟..对吗? @Jamesonthedog,可能是你的答案可以在需求的重点修改 – Vikrant