2012-11-02 123 views
0

我使用Symfony2.1与Doctrine2.1AJAX避免重复的代码

我想使用AJAX对我的网站的许多功能,编辑标题,速度的文章,即时创建一个实体等

我的问题很简单:

我需要创建一个jQuery函数为每个functionnality,就像这样:

$('#specific-functionality').bind('click', function(e){ 

    var element = $(this); 
    e.preventDefault(); 

    // the call 
    $.ajax({ 
     url: element.attr('href'), 
     cache: false, 
     dataType: 'json', 
     success: function(data){   

     // some custom stuff : remove a loader , show some value, change some css 

     } 
    }); 
    }); 

这听起来非常沉重的我,所以我想知道如果JS端有任何框架,或者我可以用来避免这种情况的特定方法。我正在考虑根据响应类型(html_content,boolean,integer)对项目进行重组,但也许已经存在很好的处理它的东西!

回答

0

相反的$('#specific-functionality').bind('click', function(e){,试试这个:

$(".ajax").click(function(){ 

    var url = $(this).attr("href") ; 
    var target = $(this).attr("data-target") ; 
    if (target=="undefined"){ 
     alert("You forgot the target"); 
     return false ; 
    } 

    $.ajax(.... 

,而在HTML

<a class="ajax" href="..." data-target="#some_id">click here </a> 

我认为这是最简单的解决方案。如果你想通过ajax工作一些链接,只需给它类“ajax”,并把data-target放到应该输出结果的地方。所有自定义的东西都可以放在这些data-something属性中。

+0

更好,谢谢!我正在查看StakOverflow的投票系统,它似乎在使用相同的概念! –

1

从我的理解,你要求的JQuery ajax方法更轻的版本。有直接的get/post方法,而不是使用ajax。

$.get(element.attr('href'), {'id': '123'}, 
    function(data) { 
     alert(data); 
    } 
); 

配置错误功能

$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);}) 
.error(function (XMLHttpRequest, textStatus, errorThrown) { 
         var msg = jQuery.parseJSON(XMLHttpRequest.responseText); 
         alert(msg.Message); 
}); 

此外,您还可以通过回调函数做任何同步操作一样

function LoadData(cb) 
{ 
    $.get(element.attr('href'), { 'test': test }, cb); 
} 

并调用

LoadData(function(data) { 
alert(data); 
otherstatements; 
}); 

对于进度条,您使用JQuery ajaxStart和ajaxStop函数而不是手动隐藏和显示它。请注意,该页面上的每个JQuery AJAX操作都会被触发。

$('#progress') 
    .ajaxStart(function() { 
    //disable the submit button 
    $(this).show(); 
    }) 
    .ajaxStop(function() { 
    //enable the button 
    $(this).hide(); 
    }); 
+0

你给我看的非常有用的技巧!谢谢 !! –