我的主页面中有以下代码,试图拉动AJAX JSON。 它只需要在每页滚动上显示10个额外的产品。并且目前它只显示加载器Circle div,它应该在加载后删除 - 但没有任何内容正在加载。
var handler = null;
var page = 1;
var isLoading = false;
var apiURL = 'ajax/api.php'
function onScroll(event) {
// Only check when we're not still waiting for data.
if(!isLoading) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() >
$(document).height() - 100);
if(closeToBottom) {
loadData();
}
}
};
function loadData() {
isLoading = true;
$('#loaderCircle').show();
$.ajax({
url: apiURL,
dataType: 'jsonp',
data: {page: page}, // Page parameter to make sure we load new data
success: onLoadData
});
};
// Receives data from the API, creates HTML for images
function onLoadData(data) {
isLoading = false;
$('#loaderCircle').hide();
// Increment page index for future calls.
page++;
// Create HTML for the images.
var html = '';
var i=0, length=data.length, image;
for(; i<length; i++) {
image = data[i];
html += '<li>';
// Image tag
html += '<img src="products/200/'+p_id+'.jpg" ">';
// Image title.
html += '<p>'+p_name+'</p>';
html += '</li>';
}
// Add image HTML to the page.
$('#tiles').append(html);
};
我的PHP JSON调用
<?php require_once('../inc/config.php');
$page = $_REQUEST['page'];
$items = '10';
$start = (($page * $items) - $items);
$end = ($page * $items);
$result = mysql_query("SELECT p_id, p_name FROM products ORDER BY p_id ASC LIMIT $start, $end");
$products = array();
while($product = mysql_fetch_array($result, MYSQL_ASSOC)) {
$products[] = ($product);
}
$output = json_encode($products);
echo $output;
?>
php显示的JSON如下(示例数据):
[{"p_id":"1","p_name":"ASOS Pleated Swing Mac"},{"p_id":"2","p_name":"ASOS Midi Belted Coat"},{"p_id":"3","p_name":"ASOS Zig Zag Coat"},{"p_id":"4","p_name":"Collarless Quilted Leather Biker with Ribbed Sleeve"},{"p_id":"6","p_name":"TFNC Dress with Wrap Front in Flocked Heart"},{"p_id":"7","p_name":"Striped Skater Dress"},
{"p_id":"8","p_name":"Metallic Wrap Dress"},{"p_id":"9","p_name":"Strapless Dress With Neon Belt"},{"p_id":"10","p_name":"Darling Floral Border Print Dress"},{"p_id":"11","p_name":"Dip Hem Chiffon Dress With Printed Top"}]
总的来说,它并没有将数据加载到html中。有人可以解释一下我可能要做什么或者我可能做错了什么。 (这是使用wookmark插件 - 但不应影响任何东西)
答案 0 :(得分:0)
问题是您已将jQuery AJAX dataType
设置为jsonp
,但您的api.php
正在输出JSON,不是 JSONP。
要解决此问题,请将dataType
更改为json
:
$.ajax({
url: apiURL,
dataType: 'json',
data: {page: page}, // Page parameter to make sure we load new data
success: onLoadData
});
或者更改您的api.php
文件以输出JSONP数据:
$json = json_encode($products);
$output = isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;