AJAX JS循环 - 更简单的方法来做多个帖子?

时间:2015-03-26 19:44:21

标签: javascript jquery ajax

我有一个使用AJAX的大表格,所以保存。它使用存储在外部JS文件中的一堆JS。它们看起来像这样:

function milestone09() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone09').serialize(), function(data) {
    $("#errorText_milestone09").html(data.errorText_milestone09);
    $("#resultImg_milestone09").html(data.resultImg_milestone09);
    $("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}

function dateExp09() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#dateExp09').serialize(), function(data) {
    $("#errorText_dateExp09").html(data.errorText_dateExp09);
    $("#resultImg_dateExp09").html(data.resultImg_dateExp09);
    $("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}

function milestone10() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone10').serialize(), function(data) {
    $("#errorText_milestone10").html(data.errorText_milestone10);
    $("#resultImg_milestone10").html(data.resultImg_milestone10);
    $("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}

function dateExp10() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#dateExp10').serialize(), function(data) {
    $("#errorText_dateExp10").html(data.errorText_dateExp10);
    $("#resultImg_dateExp10").html(data.resultImg_dateExp10);
    $("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}

等等,有这样的触发器:

$("document").ready(function() {

$("#milestone09").blur(milestone09);
$("#dateExp09").blur(dateExp09);
$("#milestone10").blur(milestone10);
$("#dateExp10").blur(dateExp10);

})

这只是我所拥有的许多部分 - 而且它们运行良好。问题是,我现在正在制作一个包含大量用户输入数据表的表单,这会将这些触发器和函数增加到100以上。我必须有一种更简单的方法来编写这个JS,而不必像这样单独定义它们,当然?每个文本输入字段的id和名称与触发器和后续函数名称一致。所以我不能使用某种循环函数,或者什么?建议欢迎!

是的,我正在使用jQuery。

1 个答案:

答案 0 :(得分:4)

一种非常简单的方法是获取ID并将其插入正确的位置:

function blurHandler() {
    var id = this.id;
    $.post('./post.3.AIGs2GRA.php?data=' + secData, $('#'+id).serialize(), function(data) {
        $("#errorText_"+id).html(data['errorText_'+id]);
        $("#resultImg_"+id).html(data['resultImg_'+id]);
        $("#errorStatusReport").html(data.errorStatusReport);
    }, 'json' );
}

// If you also have textareas or selects, change this
$('input').blur(blurHandler);
相关问题