Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

jquery ajax请求中嵌套的ajax请求不断重复执行

想使用ajax实现,加载评论时,将评论的回复也加载显示出来,但加载评论的回复时,执行加载回复的ajax代码不断重复执行,不断重复请求,检查发现加载评论的回复时for循环里i的值,一直为0。请问这是为什么,该如何解决?已经尝试过async:false,不行;初始以为是两个for循环都用i的缘故,将加载评论回复的i改为j也不行

    //加载已有评论
    function setCommentList(Id,commentbox) {
$.ajax({
type:"POST",
url:"/commentSelect",
dataType:"json",
data:{"Id":Id},
success:function(data){
for(var i = 0;i<data.length;i++) {
    var commentTemp= '<p class="comment-text"><span class="user">'+data[i].info+':</span>'+data[i].commentContent+'</p>'+
    '<p class="comment-time">'+data[i].commentTime+'</p>';
    var commentContent = document.createElement("div");
    commentContent.innerHTML = commentContent.innerHTML + commentTemp
    commentbox.appendChild(commentContent);
    console.log("评论数量"+data.length);
    setComment2List(data[i].commentId,commentContent);
}
},
error:function(){
alert("加载评论发生错误");
}
});
    }

    //加载评论的回复
    function setComment2List(commentId,commentContent) {
$.ajax({
type:"POST",
url:"/comment2Select",
dataType:"json",
async:false,
data:{"commentId":commentId},
success:function(data2){
console.log("@@@");
for(var j=0;j<data2.length;j++) {
    console.log("bug"+j);
    var comment2Temp= '<p class="comment-text"><span class="user">'+data2[j].info+':</span>'+data2[j].comment2Content+'</p>'+
    '<p class="comment-time">'+data2[j].comment2Time+'</p>';
    var comment2Content = document.createElement("div");
    comment2Content.innerHTML = commentContent.innerHTML + comment2Temp
    commentContent.appendChild(comment2Content);
    setComment2List(data2[j].commentId,commentContent);
}
},
error:function(){
alert("加载评论的回复发生错误");
}
});
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你在setComment2List 的ajax success一直重复调用setComment2List自己``只要setComment2List的ajax能进success就会一直重复调用啊··复制也不要太懒··


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...