如何通过 ajax 在 html 中追加作为循环顺序?



我开始学习回调函数,我在回调后附加了html!当我在for loop中使用ajax回调函数时,它不像循环顺序那样附加!它随机附加在正文eg.1,4,2,3中。我想附加为循环顺序 (1,2,3,4(,但不等待一个 ajax 完成?

<html>
<body>
<script>
var AJAX = {
call : function(id,callback) {
$.ajax({
url : "sample.php",
data : {id:id},
success : callback
})
}
};
for(var i =1;i < 5;i++) {
AJAX.call(i,function(html){
$("body").append(html);
});
}
</script></body></html>

样品.php

<?php
if(isset($_GET['id'])) {
echo "<h".$_GET['id'].">This is heading ".$_GET['id'];
}
这是标题 1 这是标题 4 这是标题 2 这是标题 3

您是否考虑插入将在回调时填充正确内容的空容器?

for(var i = 0; i < 5; i++) {
$('body').append('<div id="div' + i + '"></div>');
(function(){
var x = $('#div' + i);
AJAX.call(i,function(html){
x.append(html);
});
})();
}

我认为您可以尝试从服务器获得的每个html下订单。并按照给定的命令将其应用于body

for (var i = 1; i < 5; i++) {
var temp = i;
(function(temp) { // use closure to save i
AJAX.call(i,
function(html) {
var $html = $(html).data('order', temp),
$children = $('body').children();
if ($children.length === 0) { // the body is empty yet
$('body').append($html);
} else { // some requests has return from server, and body is not empty now
$children.each(function(index) {
var order = parseInt($(this).data('order'), 10);
if (index === $children.length - 1) { // last children
// insert before or after by order
temp > order ? $(this).after($html) : $(this).before($html);
} else {
var nextChildOrder = parseInt($children.eq(index + 1), 10);
if (temp < order) { // insert before
$(this).before($html);
} else if (temp > order && temp < nextChildOrder) { // insert after
$(this).after($html);
}
}
});
}
});
})(temp);
}

您可以添加一个数组,然后在 ajax 调用后正常打印它。

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script>
var order = new Array();
function add2arrayOrder(i,html)
{
order[i]=html;
//alert(i);
}
var AJAX = {
call : function(id,callback) {
$.ajax({
url : "sample.php",
data : {id:id},
success : function(html) 
{
add2arrayOrder(id,html);
}
})
}
};
// make Ajax calls
for(i =1;i < 5;i++) 
{
AJAX.call(i,function(html)
{
add2arrayOrder(i,html);
//alert(order[i]);
});
}
// wait a little and print
setTimeout(function(){
for(i=1;i < 5;i++) 
{
$("body").append(order[i]);
}  
},500);
</script>
</body>
</html>

最新更新