现在我的代码只加载 1 页 (load.php?cid=1 但我想加载 5-8 (cid=1,cid=2,cid=3,cid=4,cid=5, cid=6,cid=10 ...等)在不同的div中。
我将如何实现它?
$(document).ready(function() {
function loading_show() {
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loading_Paging').fadeOut 'fast');
}
function loadData(page) {
loading_show();
$.ajax({
type: "POST",
url: "load.php?cid=1",
data: "page=" + page,
success: function(msg) {
$("#container_Paging").ajaxComplete(function(event, request, settings) {
loading_hide();
$("#container_Paging").html(msg);
});
}
});
}
最佳答案
正如 JimL 提到的,我会给页面上的每个元素一个公共(public)类,给每个元素一个唯一的数据属性,如 data-cid="1"
,迭代每个元素以获取 cids并为每个调用 ajax 函数。
我更进一步,使用 Promise 获取所有 Ajax 响应,然后在 Promise 解决时(当所有 Ajax 请求完成时)加载所有数据。
HTML:
<div id="loading_Paging"></div>
<div class="myElements" data-cid="1"></div>
<div class="myElements" data-cid="2" ></div>
<div class="myElements" data-cid="3" ></div>
<div class="myElements" data-cid="4" ></div>
<div class="myElements" data-cid="5" ></div>
<div class="myElements" data-cid="6" ></div>
<div class="myElements" data-cid="7"></div>
<div class="myElements" data-cid="8" ></div>
jQuery:
$(function() {
var page = 'some string...'
loadData(page);
function loadData(){
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
// loop through each image element
// calling the ajax function for each and storing the reponses in a `promise`
var promises = $('.myElements').map(function(index, element) {
var cid = '&&cid=' + $(this).data('cid'); // get the cid attribute
return $.ajax({
type: "POST",
url: 'load.php',
data: "page=" + page +cid, //add the cid info to the post data
success: function(msg) {
}
});
});
// once all of the ajax calls have returned, te promise is resolved
// and the below function is called
$.when.apply($, promises).then(function() {
// arguments[0][0] is first result
// arguments[1][0] is second result and so on
for (var i = 0; i < arguments.length; i++) {
$('.myElements').eq(i).html( arguments[i][0] );
}
$('#loading_Paging').fadeOut('fast');
});
}
});
我在示例中使用的 PHP:
<?php
if (isset($_POST['cid']) ){
// this is just a contrived example
// in your code youd use the cid to
// get whatever data you need for the current div
echo 'This is returned message '.$_POST['cid'];
}
?>
关于Php Ajax - 一个页面中的多个调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923543/