Ajax和Json查询不起作用

时间:2013-02-14 15:54:03

标签: php javascript jquery ajax

我在使用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']));
}
?>

1 个答案:

答案 0 :(得分:1)

您不需要两个请求。在第一个请求中指定dataType: 'json'会告诉jQuery将响应解析为JSON。

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},
         dataType: 'json',
         success: function(data){
            var id = data.id;
            document.location.hash = id;   
            known_images[id] = data;
            $("#lblName").html(data.name);
            $('#lblRating').html(data.average + " (" + data.votes + ") (<a href='User.php?uid=" + data.userid + "'>" + data.username + "</a>)");
         }
     });

     $('#design').attr('src','img/boxes/'+knownid+'.png');


}