Я пытаюсь вызвать данные из API и включить их на свою HTML-страницу. Данные возвращаются в формате JSON, однако я пытаюсь добавить их в элемент списка на странице, но, похоже, он не хочет сотрудничать.

    function getGames() {
    $query = "SELECT * FROM games ORDER BY name";

    try {
        global $db;
        $games = $db->query($query);
        $games = $games->fetchAll(PDO::FETCH_ASSOC);
        echo '{"game": ' .json_encode($games) .'}';
    } catch (Exception $ex) {
        echo '{"error": {"text":' .$ex->getMessage() .'}}';
    }
}

Выше мой вызов API.

Ниже приведены мои методы вставки данных на страницу:

// root URL for restful web services 
var rootURL ="http://localhost/GameReviewWebsite/api/games";
//when thr DOM is ready
$(document).ready(function(){
    findAll();
   // findById();
});

var findAll=function(){
    console.log('findAll');
    $.ajax({
        type: 'GET',
        url: rootURL,
        dataType: 'json', // data type of response
        success: renderList
    });
};

function renderList(data){
    list = data.games;
    $('#gameList li').remove();
    $.each(list, function(index, game){
        $('#gameList').append('<li><a href="#" id="' +game.id+'">'+game.name+'</a></li>');
    });
 }

И вот данные, которые я получаю:

    {"game": [
{"id":"2","name":"FIFA 19","developer":"EA Sport","genre":"Sports","review":"2","description":"A game based on real world soccer teams and tournaments."},
{"id":"1","name":"Rocket League","developer":"Psyonix","genre":"Sports","review":"4","description":"A soccer-like game where players driver rocket propelled cars around an arena."},
{"id":"4","name":"SCUM","developer":"Gamepires","genre":"Survival","review":"5","description":"A game where the user plays a human that must survive in a future dominated by robots."},
{"id":"6","name":"Trials Fusions","developer":"RedLynx","genre":"Sports","review":"1","description":"A game where players take control of a skilled motocross rider that tries to navigate through a course filled with obstacles"}
]}
-2
iQuain 24 Окт 2018 в 03:50

2 ответа

Лучший ответ

Неправильные имена переменных,

list = data.games;

Должно быть

list = data.game;

Так как игра - это имя игрового массива

     {"game": [
{"id":"2","name":"FIFA 19","developer":"EA Sport","genre":"Sports","review":"2","description":"A game based on real world soccer teams and tournaments."},
{"id":"1","name":"Rocket League","developer":"Psyonix","genre":"Sports","review":"4","description":"A soccer-like game where players driver rocket propelled cars around an arena."},
{"id":"4","name":"SCUM","developer":"Gamepires","genre":"Survival","review":"5","description":"A game where the user plays a human that must survive in a future dominated by robots."},
{"id":"6","name":"Trials Fusions","developer":"RedLynx","genre":"Sports","review":"1","description":"A game where players take control of a skilled motocross rider that tries to navigate through a course filled with obstacles"}
]}
-1
YouriKoeman 24 Окт 2018 в 00:57
function renderList(data){
    list = data.game;
    $('#gameList li').remove();
    $.each(list, function(index, game){
        $('#gameList').append('<li><a href="#" id="' +game.id+'">'+game.name+'</a></li>');
    });
 }

У вас есть опечатка в назначении переменной списка, это должно быть list = data.game, а не list = data.games

-1
Yang Daniel 24 Окт 2018 в 00:58
52959652