我通过封装在一个for-循环中来发出多个ajax请求:
for(var o = 1; o <= 2; o++)
{
$.ajax({
type: 'GET',
url: 'lib/terrain.php',
dataType: 'html',
data: {o: o},
success: function(data) {
var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
console.log(data);
},
error: function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
});
k=o;
} 从后端获取有关不同对象的信息:
if(isset($_GET['o']))
{
$object_query = mysql_query("SELECT * FROM objects");
$objects = array();
while($object_row = mysql_fetch_row($object_query))
{
$objects[] = $object_row; //Information about objects
}
$count_objects = count($objects); //Count how many objects it is
$slump_objects = rand(1, $count_objects); //Sell of which objects that shoul be viewd at the map.
var_dump($objects[$slump_objects]);
}如您所见,我对我的后端进行了两次ajax调用。我的问题是,有时它只从后端得到一个值,而不是两个值。有时它得到两个值,这是正确的。BUt问题是,有时它只得到一个值,而另一个值为空。
为什么会这样呢?
发布于 2014-08-28 12:48:28
错误出现在PHP代码中:
$slump_objects = rand(1, $count_objects); //Sell of which objects that shoul be viewd at the map.
var_dump($objects[$slump_objects]);如果$slump_objects的值等于$count_objects (数组大小),那么var_dump($objects[$slump_objects])返回NULL。
PHP从索引0开始,最后一个索引是($count_objects-1),因此将其中一个语句更改为:
$slump_objects = rand(0, $count_objects-1);或
var_dump($objects[$slump_objects-1]);发布于 2014-08-28 12:55:11
由于ajax是异步的,您的循环将立即完成,相反,您应该使ajax函数递归,从已完成的回调调用它的self:
function doAjax(){
var total = 2;
var counter = 0;
function recursiveAjax(){
$.ajax({
//...
done:function(){
counter++;
//call again
if(counter < total) recursiveAjax();
}
});
}
//call the first time
recursiveAjax();
}发布于 2014-08-28 12:52:24
下面是一个使用done()进行第二个调用的示例-- http://api.jquery.com/jquery.ajax/
$.ajax({
type: 'GET',
url: 'lib/terrain.php',
dataType: 'html',
data: {o: 1},
}).done(function(data) {
var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
console.log(data);
$.ajax({
type: 'GET',
url: 'lib/terrain.php',
dataType: 'html',
data: {o: 2},
}).done(function(data) {
var objectRuta = Math.floor((Math.random() * 100) + 1); //Slumpar tal mellan 1 & 100
angular.element('.click#'+objectRuta).addClass('object').html($("<img src='images/potion.png' title='"+data+"'>"));
console.log(data);
}).fail(function() {
function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
})
}).fail(function() {
function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
});当然,这可以做得更整洁,这只是给你一个技术的想法。
https://stackoverflow.com/questions/25548976
复制相似问题