0

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']));
}
?>
4

1 に答える 1

1

2つのリクエストは必要ありません。最初のリクエストで指定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');


}
于 2013-02-14T16:03:16.317 に答える