jQuery AJAX替换返回数据中的单词有时无法正常工作



我需要从返回的AJAX数据中替换一些单词。我是这样做的:

function loadfile(){
    $.ajax({
        type: 'post',
        url: 'donachrichten.php',
        data: {mach: "loadfile", kontaktfile: kontaktfile},
        success: function(data){
                var kontent = data;
                var user1 = $(".user1").attr("id");
                var user2 = $(".user2").attr("id");
                var profilpic1 = $(".profilpic1").attr("id");
                var profilpic2 = $(".profilpic2").attr("id");
                var data1 = kontent.replace(new RegExp(user1, "g"), profilpic1);
                var data2 = data1.replace(new RegExp(user2, "g"), profilpic2);
                $("#chatnow").html(data2);
        }
    });
} 

70% 的情况下它工作正常,但在 30% 的情况下,chatnowdiv 充满了undefinedundefined....

这里可能有什么问题?

编辑:

这是在加载文件之前所称的:

function selectkontakt(z){
    $("#loadnew").empty();
    $("#loadold").empty();
    kontaktfile = $(z).attr('id');
    kontakte(); // the user1/user2 and profilpic1/profilpic2 classes are comming from here, also though AJAX
    loadfile();
    $("#textarea").show();
    $('#usermsg').focus();
}

所以我想这只是一个糟糕的时机,有没有办法修复时机?

这可能是由于 id 或元素不存在。 如果您使用 ajax 加载该用户元素。 在该元素加载/AJAX 成功后使用此函数。

我是这样解决的:

function selectkontakt(z){
    $("#loadnew").empty();
    $("#loadold").empty();
    kontaktfile = $(z).attr('id');
    kontakte();
    loadfile().done(kontakte); // HERE
    $("#textarea").show();
    $('#usermsg').focus();
}

所以时机不能再被打破了:)

最新更新