【问题标题】:jQuery AJAX replacing words in returned data sometimes not working correctjQuery AJAX 替换返回数据中的单词有时无法正常工作
【发布时间】:2015-03-28 10:37:09
【问题描述】:

我需要从返回的 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% 的情况下,chatnow div 充满了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();
}

所以我想这只是一个糟糕的时机,有什么办法可以解决这个时机吗?

【问题讨论】:

    标签: jquery ajax replace


    【解决方案1】:

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

    【讨论】:

    • 如果使用ajax方式加载 $(".user1").attr("id");这些元素你可以调用 loadfile(); kontakte()的ajax成功函数中的函数;
    【解决方案2】:

    我是这样解决的:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多