我的.each没有运行,我也不知道为什么?

时间:2018-10-24 00:50:33

标签: jquery html

我正在尝试从API调用数据并将其包含在HTML页面中。数据以JSON格式返回,但是,我试图将其追加到页面上的列表元素中,但似乎不希望合作。

 var qsarr = window.location.href.split('?');
  if(qsarr.length > 1)
  var qs=qsarr[1];

上面是我的API调用。

以下是我将数据插入页面的方法:

    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() .'}}';
    }
}

这是我收到的数据:

// 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>');
    });
 }

2 个答案:

答案 0 :(得分:-1)

变量名称错误

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 :(得分:-1)

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