缩小相同模式的呼叫的ajax请求

时间:2015-01-10 14:30:32

标签: javascript jquery ajax

大家好,因为内存和时间问题,只想缩小此代码 我只是想缩小它,因为ajax的模式调用相同

我使用ajax函数在css类中获取我的内容 请仔细查看我的代码及其模式

        $("#poto").click(function (e) {
$("#loadimg").show(); 
jQuery.ajax({ url: "photos.php", 
         cache: true,
            success:function(response){
                $(".homefeed").html(response);
                  $("#elementcontainer").show();
                $("#loadimg").hide(); 
            },
            });return false;
    });


            $("#mkt").click(function (e) {
$("#loadimg").show(); 
jQuery.ajax({ url: "newm.php", 
         cache: true,
            success:function(response){
                $(".homefeed").html(response);
                  $("#elementcontainer").hide();
                $("#loadimg").hide(); 
            },
            });return false;
    });

        $("#invite").click(function (e) {
$("#loadimg").show(); 
jQuery.ajax({ url: "invite/index.php", 
         cache: true,
            success:function(response){
                $(".homefeed").html(response);
                $("#loadimg").hide(); 
            },
            });return false;
    });

......比这更进了10次

有什么方法可以缩小它,因为它花费了太多时间来加载.homefeed类中的内容并且还需要很多字节/

任何方式如何实现它?感谢

1 个答案:

答案 0 :(得分:0)

声明一个新函数,它将处理ajax请求和成功响应:

function ajaxLoadImage(url, showElementContainer) {
    $("#loadimg").show(); 
    jQuery.ajax({ 'url': url, 
        cache: true,
        success: function(response){
            if(showElementContainer) {
                $("#elementcontainer").show();
            }
            $(".homefeed").html(response);
            $("#loadimg").hide(); 
        },
    });
    return false;
}

然后当你绑定click事件时,只需执行:

$("#poto").click(function (e) { 
    ajaxLoadImage("photos.php", true);
});