从ajax请求返回时,让jQuery在DIV中创建一行新行

Getting jQuery to make a new line inside a DIV when returning from an ajax request

本文关键字:创建 新行 一行 DIV 返回 请求 ajax jQuery      更新时间:2023-09-26
 <script>   
     $.ajax
         ({
             url: "../getStatus/",
             dataType: 'json',
             success: function(json) 
             {            
                $('#ajaxLog').html(json.status+"<br/>");
             }
         });
</script>
 //Need this section to make a new line when refreshed
<div id = ajaxLog style="width:50%"></div>

这需要是一个累积的,返回到网页的消息。每次进程启动/停止/挂起时,都会显示它。当保持在一个状态时,显示的消息不会一直说stopped/started/等等——而是每次这些状态改变时都会显示,然后它不会不断地重新显示——不像jquery.append((那样。

所需

started 10:48
stoped 10:50
Started 12:53
suspended 3:34
Started 3:40

不需要

started 10:48
started 10:48
started 10:48
started 10:48
started 10:48
started 10:48
started 10:48
stoped 10:50
.
.

等等

(就像append((一样(

    <script>   
    //Use this
    last=null;
     $.ajax
                ({
                    url: "../getStatus/",
                    dataType: 'json',
                    success: function(json) 
                {
                        //Replace this line
                        //$('#ajaxLog').html(json.status+"<br/>");
                        //with this:
                        if(last!=json.status)
                        {
                            $('#ajaxLog').append(json.status+"<br/>");
                            //or: $('#ajaxLog').append('<p>'+json.status+'</p>');
                            last=json.status;
                        }
                 }
             });
</script>
 //Need this section to make a new line when refreshed
<div id = ajaxLog style="width:50%"></div>

HTML中没有新行这样的东西。您可以使用<br/>标记来实现新行语义:

$('#ajaxLog').append(json.status + '<br/>');

或者将内容放入div:

$('#ajaxLog').append('<div>' + json.status + '</div>');

此外,您应该使用.append()方法而不是.html(),以避免每次调用ajaxLogdiv时都覆盖其内容。

在HTML中添加换行符?

success: function(json) 
{
    $('#ajaxLog').html("<br />" + json.status+);
}

除非我误解了这一点,否则您正在调用html((方法,它将替换div的全部内容。您真的想把结果(在新行上(附加到div中已经存在的内容上吗?

如果我没有正确理解这个问题,我深表歉意。

ajax设置不应该有一个额外的吗

data: ''

所以它看起来像

url: '../getStatus/', data: '', dataType: 'json', success: ...

我很确定我在什么地方读过这篇文章。