Javascript + Ajax + Django - 聊天应用程序问题

时间:2015-06-05 13:33:45

标签: javascript jquery python ajax django

所以我在django + javascript + ajax

中有这个应用程序
var friends = "{{friend}}";
function LoadJson(){ //start function
    $.getJSON( "/messages/message/friend="+friends, function( data ) {
        var items = [];
        var lastitem = parseInt($("#showdata div:last-child").attr("id"));
    if (lastitem !== lastitem) {
        var lastitem = 0;
    }
    $.each( data, function( key, val ) {

我想在这里添加它,读取消息,如果大于30,如果它不包含空格,它将每隔30个字母添加一个空格:

        if ( key > lastitem ) {
            var str = val.msg;
            var search = str.search(" ")
            if (str > 30) {
                if ( (search == -1) || (search > 30) ) {
                    newVal = str.replace(/(.{30})/g, "$1\n");
                    console.log(newVal)
                }
            }

但每次我向基础应用程序添加内容时,应用程序都会崩溃并多次显示最后一条消息。

        if ( key > lastitem ) {
            $("#showdata").append("<div class='well well-lg lighter row col-md-12' id='" + key + "'>"+"<span class='pull-left'><span class='sender col-md-3'>"+val.user+"</span>" + "<span class='message col-md-6' style='margin-left:30px;'>" + val.msg + "</span></span></br><small class='pull-right col-md-3'>"+ val.time + "</small></div>");
            $('#bottom').scrollTop($('#bottom').prop("scrollHeight"));
            $(window).scrollTop($(document).height());
        };
    });
});
setTimeout(LoadJson, 5000);

};

我真的会得到任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

这暂时解决了我的问题:

var friends = "{{friend}}";
function LoadJson(){ //start function
$.getJSON( "/messages/message/friend="+friends, function( data ) {
    var items = [];
    var lastitem = parseInt($("#showdata div:last-child").attr("id"));
    if (lastitem !== lastitem) {
        var lastitem = 0;
    }
    $.each( data, function( key, val ) {
        if (val.msg) {
            var str = val.msg;
            var search = str.search(" ")
        }
        if ( key > lastitem ) {
            if ( (search == -1) || (search > 30) ) {
                newVal = str.replace(/(.{30})/g, "$1\n");
                $("#showdata").append("<div class='well well-lg lighter row col-md-12' id='" + key + "'>"+"<span class='pull-left'><span class='sender col-md-3'>"+val.user+"</span>" + "<span class='message col-md-6' style='margin-left:30px;'>" + newVal + "</span></span></br><small class='pull-right col-md-3'>"+ val.time + "</small></div>");
            }
            else {
                $("#showdata").append("<div class='well well-lg lighter row col-md-12' id='" + key + "'>"+"<span class='pull-left'><span class='sender col-md-3'>"+val.user+"</span>" + "<span class='message col-md-6' style='margin-left:30px;'>" + val.msg + "</span></span></br><small class='pull-right col-md-3'>"+ val.time + "</small></div>");
            }
            $('#bottom').scrollTop($('#bottom').prop("scrollHeight"));
            $(window).scrollTop($(document).height());
        };
    });
});
setTimeout(LoadJson, 5000);

};