1

大家好,这是我在这个论坛的第一篇文章。

我有这个功能

function TestePresenca(){
var msg = ''
$('#teste tbody tr').each(function(){
    var MemberId;
    var ClassId;
    var PresenceDate;
    var OClasse;

    var DataPre = $('#data_presenca').val();
    var TotBiblia = $('#tot_biblia').val();
    var TotOferta = $('#tot_ofertas').val();

    $(this).find('td').each(function(){
        if($(this).index() == 0){
            MemberId = $(this).text();
        }

        if($(this).index() == 3){
            $(this).closest('tr').find("select").each(function(){
                ClassId = this.value;
            })
        }

        if($(this).index() == 4){
            OClasse = $(this).text();
        }           
    });

    $.ajax({
        type: 'POST',
        url: BASE + '/save_list_presence',
        data: {pMemberId: MemberId, pClassId: ClassId, pOClasse: OClasse, pDataPre: DataPre, pTotBiblia: TotBiblia, pTotOferta: TotOferta},
        success: function(retorno){
            msg += retorno;
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert('Erro!');
        }
    });
});
alert(msg);}

我的问题是“alert(msg)”在没有消息的情况下触发,在调试时我看到它的触发,然后每个和 ajax 执行之后,“msg”变量在最后被填充,但是警报之前被触发。

有人知道我该如何解决吗?

提前致谢。

4

2 回答 2

0

AJAX 是异步的——它下面的代码可能在 AJAX 调用完成之前运行。

于 2013-04-18T19:20:30.313 回答
-1

Try to use this async: false in your ajax call:

$.ajax({
        type: 'POST',
        url: BASE + '/save_list_presence',
        async: false,
        ...

From the jQuery.ajax() API Docs

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

于 2013-04-18T19:22:07.957 回答