我在使用 Ajax 检索数据时遇到了一些问题。有人可以告诉我我的代码有什么问题吗?我觉得这与我在同一个函数中使用 JSON 和 Ajax 的事实有关吗?
jQuery
function updateImage() {
var knownid = document.location.hash.substring(1); // remove #
$.ajax({ //Make the Ajax Request
type: "POST",
url: "testimagelook.php", //file name
data: {boxid: knownid},
success: function(server_response){
$.getJSON("testimagelook.php", function(data) {
var id = data.id;
document.location.hash = id;
known_images[id] = [];
known_images[id] ['name'] = data.name;
known_images[id] ['average'] = data.average;
known_images[id] ['votes'] = data.votes;
known_images[id] ['username'] = data.username;
known_images[id] ['userid'] = data.userid;
});
}
});
$('#design').attr('src','img/boxes/'+knownid+'.png');
$("#lblName").html(known_images[knownid]['name']);
$('#lblRating').html(known_images[knownid] ['average'] + " (" + known_images[knownid] ['votes'] + ") (<a href='User.php?uid=" + known_images[knownid] ['userid'] + "'>" + known_images[knownid] ['username'] + "</a>)");
}
我的 Ajax 连接的 PHP 文件如下:
PHP
<?php
include('config.php');
if (isset($_POST['boxid']))
{
$knownid = $_POST['boxid'];
$query = mysql_query("SELECT b.id as boxid, b.name, b.date_added, u.username, u.id as userid, u.active, b.active, b.active_admin, b.average as average, b.votes as votes FROM BOXES b, USERS u WHERE b.user_id = u.id AND b.id >= $knownid LIMIT 0,1");
$userData = mysql_fetch_array($query, MYSQL_ASSOC);
echo json_encode(array("id" => $userData['boxid'], "name" => $userData['name'], "average" => $userData['average'], "votes" => $userData['votes'], "username" => $userData['username'], "userid" => $userData['userid']));
}
?>