如何使用一个函数在几个ajax调用

how can use of a function in several ajax call?

本文关键字:几个 ajax 调用 一个 何使用 函数      更新时间:2023-09-26

为了避免重复,我想在几个ajax调用中使用一个函数。怎么样?

:

//use of content this function in other function(ajax call)
$(function num_bg () {
    var total = $('.pag a', '.ser').size();
    if (total == 0) {
        $('.number').css('display','none');
    }
});
// First ajax call
    function pagination(e) {
    e.preventDefault();
    var dataObj = $('form').serialize();
    $.ajax({
        type: "POST",
        dataType: "html",
        url: 'dirc',
        data: dataObj,
        cache: false,
        success: function (html) {
            var $html = $(html);
                $('#num_count').replaceWith($html.find('#num_count'));
                $('tr#paginate').replaceWith($html.find('tr#paginate'));
                $('.pagination').replaceWith($html.find('.pagination'))
                $('#erro_find').remove();
        num_bg (); // This is same function above (this don't work)
        }
    });
    return false;
}
$('form').live('change', pagination);
$('.pag a').live('click', pagination);
$('#input').live('keyup', pagination);

 //Second ajax call
$('#delete').click(function(e){        
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: 'diuarsl',
        data: dataString,
        cache: false,
        success: function(html){
            var $html = $(html);                       
                    $('#num').replaceWith($html.find('#num_count'));
                    $('tr#pag').replaceWith($html.find('tr#paginate'));
                    $('.pag').replaceWith($html.find('.pagination'));
                num_bg (); // This is same function above (this don't work)
                }
        }
    })
});

问题是您将函数包装在闭包中。闭包在这方面很有用,因为它意味着你的变量不会污染任何其他命名空间(例如window)。

删除newbg函数周围的$(...)

  // num_bg is now available as a global
function num_bg () {
    var total = $('.pag a', '.ser').size();
    if (total == 0) {
        $('.number').css('display','none');
    }
}
$( num_bg ); // invoke the function when the DOM is ready

jQuery中的$(function() { });将附加一个处理程序到DOM就绪事件。通常如果你使用的是DOM,那么你会想把所有的代码都包装在里面。

只需删除函数表达式周围的$(..)调用(并使其成为函数声明)。