将API响应附加到HTML页面 - 消失

时间:2015-04-27 08:40:53

标签: javascript html

对于作业,我正在向Github Gist API发出请求,然后将响应附加到HTML页面。然后我应该允许用户“喜欢”其中一个GISTS,然后GIST将出现在一个单独的收藏夹部分(收藏的GISTS将存储在本地存储中)。我能够发出请求,附加信息并使收藏的GIST出现在另一部分但是,列表只出现片刻然后在我点击收藏夹按钮后消失。我可以看到列表闪烁然后消失。所有其他(非最喜欢的)GIST信息也会消失,即使它不是假设。有谁能指出我正确的方向?我不允许使用任何JQuery。完整代码:http://pastebin.com/ic0juq9n

以下关键代码:     var getData = function(url)     {     如果(!REQ)     {         throw'无法创建HttpRequest。';     }

req.onreadystatechange = function()
{
    if(this.readyState === 4)
    {
        if (req.status === 200)
        {
            console.log("It worked!!");
            var info = JSON.parse(req.responseText);
            for(var key in info)
            {
                GistList.push(info[key]);
            }
        }
        else
        {
            console.log("It messed up again");
        }
    }

    for (i = 0; i < GistList.length; i++)
    {
        generateGistList(GistList[i]);
    }
}

req.open('GET', url);
req.send();

};

  function generateGistList(Gist) {

    var itemList = document.createElement('li');
    var holdURL = document.createElement('div');
    var holdID = document.createElement('div');
    var description = document.createElement('div');
    if (Gist.description === null)
    {
        description.innerHTML = "No description found";
    }
    else
    {
        description.innerHTML = "Description: " + Gist.description;
    }

    holdURL.innerHTML = "URL: " + Gist.url;
    holdID.innerHTML = "ID: " + Gist.id;
    itemList.appendChild(holdID);
    itemList.appendChild(holdURL);
    itemList.appendChild(description);
    ul.appendChild(itemList);
    list.appendChild(ul);

    var favorite = document.createElement("button");
    favorite.innerHTML = "+";
    favorite.setAttribute("gistId", Gist.id);
    itemList.appendChild(favorite);
    favorite.onclick = function()
    {
        var gistId = this.getAttribute("gistId"); //saved   
        var toBeFavoredGist = findById(gistId);

        //here you add the gist to your favorite list in the localStorage   
        and remove it from the gist list and add it to favorite list
        addFavorite(toBeFavoredGist);
        DisplayFavs();
        //removeGist(toBeFavoredGist);
     }

    }

1 个答案:

答案 0 :(得分:0)

确保您使用的是表单标签具有操作属性的表单!