我是JavaScript新手,也是json。我已经创建了一个代码,我想从json文件中获取消息以及图像。我能够获取消息,但我无法获取图像。
我在json文件中给出了图片的网址。
这是我的js代码:
fetch('http://localhost/chats.json').then(function(response){
return response.json();
console.log(response.json());
}).then(function(json){
console.log(json);
json.message.forEach(function(item){
var li=document.createElement("li");
var img=document.createElement("img");
img.src=item.url;
img.width="100px";
var text=document.createTextNode(item.msg);
li.appendChild(text);
li.appendChild(img);
document.getElementById('line').appendChild(li);
$("ul>li").each(function(i,val){
$(this).css("color",i & 1? "#FF8000" : "#8080C0");
})
})
}).catch(function(error){
window.alert('There has been a problem with your fetch operation: ' + error.message);
})
这是我的json文件:
{
"message":
[
{
"user": 1,
"msg_id":1,
"msg": "Hello, how are you?",
"url": "http://placehold.it/600/6dd9cb"
}
]
}
Edit-1这是html:
<!DOCTYPE html>
<div class="container div" style="position: absolute;">
<h2 class="panel-heading out" style="margin-right: 50px;">User1</h2>
<div class="panel panel-primary">
<div class="panel-body"> <ul id="line" style="list-style: none; font-family: Helvetica Neue"><img id="image_li"></ul> </div>
</div>
</div>
答案 0 :(得分:0)
这是显示图像的正确答案。感谢用户:5053002。
var json = { "message":
[
{
"user": 1,
"msg_id":1,
"msg": "Hello, how are you?",
"url": "https://placehold.it/600/6dd9cb"
}
]}; json.message.forEach(function(item) {
var li = document.createElement("li");
var img = document.createElement("img");
img.src = item.url;
img.width = "100";
var text = document.createTextNode(item.msg);
li.appendChild(text);
li.appendChild(img);
document.getElementById('line').appendChild(li);
$("ul>li").each(function(i, val) {
$(this).css("color", i & 1 ? "#FF8000" : "#8080C0");
}) })
谢谢你 - Jaromanda X