我正在尝试从我的 .json 文件(从服务器)获取数据并将其显示在页面上。我不太擅长 JS 语法,抱歉。
我试图仅显示文件中的一个参数,但我在屏幕上看不到任何内容。
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script>
$(function() {
$.getJSON("video.json", function(data)) {
$.each(data.NewsSources, function(i, f) {
var vid = f.Name;
$(vid).appendTo("#userdata");
});
});
});
</script>
</head>
<body>
<div id= "userdata">
<h1>This is a name</h1>
</div>
</body>
</html>
视频.json
{
"NewsSources": [
{
"ID": 2004,
"Name": "365TV Brasil",
"Description": "",
"URL": "https://www.instagram.com/365scoresbra",
"Lang": 31,
"CountryID": 21,
"LogoUrl": "",
"ImgVer": 0
}
]
}
最佳答案
你有一个小错误,你应该使用 $("#userdata").append(vid) 而不是
.$(vid).appendTo("#userdata")
data = {
"NewsSources": [{
"ID": 2004,
"Name": "365TV Brasil",
"Description": "",
"URL": "https://www.instagram.com/365scoresbra",
"Lang": 31,
"CountryID": 21,
"LogoUrl": "",
"ImgVer": 0
}]
};
$.each(data.NewsSources, function(i, f) {
var vid = f.Name;
$("#userdata").append(vid);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="userdata">
<h1>This is a name</h1>
</div>
同时在 JSFiddle .
为什么...好吧,执行 $("365TV Brasil")
是一个 jQuery 选择器,它不会选择页面上的任何内容。另一方面,在 jQuery may be complicated 中创建文本节点。因此,更好的方法是使用 jQuery append method ,它允许文本作为参数:
DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
关于jquery - 如何使用 jquery 库显示 .json 文件中的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56988951/