window.addEventListener('load',function(){
var last=0;
var sub=document.getElementById("sub");
var msg=document.getElementById('msg');
var msg_bx=document.getElementById("msg_bx");
var re=new XMLHttpRequest();
re.open("GET","handler.php?mode=begin",true);
re.onreadystatechange=function(){
if(re.status==200 && re.readyState==4){
//console.log(re.responseText);
var data=JSON.parse(re.responseText);
if(data.err_msg){
alert(data.err_msg);
}
else {
for(var o in data){
struct(data[o]);
}
}
}
}
re.send(null);
function struct(data){
s=data.sender;
m=data.msg;
t=data.time;
i=data.id;
var bx=document.createElement("div");
bx.className="msg";
msg_bx.appendChild(bx);
var sen=document.createElement("div");
bx.appendChild(sen);
sen.appendChild(document.createTextNode("Sent by:"+s));
var msg=document.createElement("div");
bx.appendChild(msg);
msg.appendChild(document.createTextNode(m));
if(i>=last){
last=i;
}
console.log(i+" "+last);
}
});
控制台数据来自::
2 2 chat.js:64
3 3 chat.js:64
4 4 chat.js:64
5 5 chat.js:64
6 6 chat.js:64
7 7 chat.js:64
8 8 chat.js:64
9 9 chat.js:64
10 9 chat.js:64
11 9 chat.js:64
{"count1":{
"id":"2",
"sender":"1",
"msg":"bbfkjvndk?",
"time":"1386494886"
},"count2":{
"id":"3",
"sender":"1",
"msg":"bubjhadljlkvdjovjj;ojkd?",
"time":"1386494931"
},"count3":{
"id":"4",
"sender":"1",
"msg":"vidhu?",
"time":"1386494982"
},"count4":{
"id":"5",
"sender":"1",
"msg":"bvfiuefhilnfdigvfuodahfasviubjcabsyvgUVHJVKJFHV9dhf79gvhkebfvkjhdovi;h7zv9jvhdsbviy7dg89hvdsbyuavgd?",
"time":"1386495013"
},"count5":{
"id":"6",
"sender":"1",
"msg":"what the hel??",
"time":"1386495367"
},"count6":{
"id":"7",
"sender":"1",
"msg":"?",
"time":"1386497097"
},"count7":{
"id":"8",
"sender":"1",
"msg":"?",
"time":"1386497097"
},"count8":{
"id":"9",
"sender":"1",
"msg":"what do u want with me??",
"time":"1386506545"
},"count9":{
"id":"10",
"sender":"1",
"msg":"so g otbjobjsd?",
"time":"1386506554"
},"count10":{
"id":"11",
"sender":"1",
"msg":"what the hell??",
"time":"1386507581"
}} chat.php:13
循环在9之后停止递增。 struct函数用于创建基本结构,并在数据作为json时调用。 最后一次增加i值,直到它达到9,然后由于某种原因而变得正常,即使我正在增加
答案 0 :(得分:0)
这是因为Javascript中的"10" >= "9"
是false
。
我怀疑data.id
是一个字符串。这也会产生i
和last
个字符串,在比较i >= last
期间,它们会被比较为字符串。
您可以在比较之前将其转换为数字:i = +data.id;
然后10 >= 9
将为true
。