我正在尝试使用javascript将JSON中的url值作为图像标记传递给HTML。
以下是json响应,我得到:
{
"remaining": 50,
"cards": [{
"suit": "SPADES",
"value": "2",
"code": "2S",
"images": {
"svg": "https://deckofcardsapi.com/static/img/2S.svg",
"png": "https://deckofcardsapi.com/static/img/2S.png"
},
"image": "https://deckofcardsapi.com/static/img/2S.png"
},
{
"suit": "CLUBS",
"value": "QUEEN",
"code": "QC",
"images": {
"svg": "https://deckofcardsapi.com/static/img/QC.svg",
"png": "https://deckofcardsapi.com/static/img/QC.png"
},
"image": "https://deckofcardsapi.com/static/img/QC.png"
}],
"success": true,
"deck_id": "ag5x22svcp8g"
}
我可以访问并解析除“ images”以外的所有其他json数据,作为实际图像。
这是我的JavaScript:
document.getElementById("card1").innerHTML = parse.cards[0].suit + ", " +
parse.cards[0].value
document.getElementById("card2").innerHTML = parse.cards[1].suit + ", " +
parse.cards[1].value
document.getElementById("card1image").src= cards[1].images.png;
这是我想放入的HTML标签。
<img id="card1image"/> //<---- this one
<div id="card1"></div>
<img id="card2image">
<div id="card2"></div>
它不会引发错误,只是不显示图像。我很确定我对getElemntByID的调用做错了。任何信息都会有所帮助。
值得注意的是,JSON对象内的url在重新加载时有所不同,因为它会从卡组中抽取随机卡。尝试将响应URL存储在变量中,但仍然无法正常工作。
答案 0 :(得分:1)
您是说parse.cards[1].images.png
吗?您缺少parse
答案 1 :(得分:1)
这是工作代码。您只需这样写您的行
parse.cards[1].images.png
您只是在代码中错过了parse
一词。
var parse = {
"remaining": 50,
"cards": [{
"suit": "SPADES",
"value": "2",
"code": "2S",
"images": {
"svg": "https://deckofcardsapi.com/static/img/2S.svg",
"png": "https://deckofcardsapi.com/static/img/2S.png"
},
"image": "https://deckofcardsapi.com/static/img/2S.png"
},
{
"suit": "CLUBS",
"value": "QUEEN",
"code": "QC",
"images": {
"svg": "https://deckofcardsapi.com/static/img/QC.svg",
"png": "https://deckofcardsapi.com/static/img/QC.png"
},
"image": "https://deckofcardsapi.com/static/img/QC.png"
}
],
"success": true,
"deck_id": "ag5x22svcp8g"
}
document.getElementById("card1").innerHTML = parse.cards[0].suit + ", " +
parse.cards[0].value
document.getElementById("card2").innerHTML = parse.cards[1].suit + ", " +
parse.cards[1].value
document.getElementById("card1image").src = parse.cards[1].images.png;
<img id="card1image" />
<div id="card1"></div>
<img id="card2image">
<div id="card2"></div>