【问题标题】:How can I display the content from the .json file with jquery library?如何使用 jquery 库显示 .json 文件中的内容?
【发布时间】:2019-07-11 12:15:28
【问题描述】:

我正在尝试从我的 .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>    

video.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")

标签: jquery json ajax getjson


【解决方案1】:

你有一个小错误,而不是$(vid).appendTo("#userdata"),你应该使用$("#userdata").append(vid)

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 元素、文本节点、元素数组和文本节点、HTML 字符串、 或 jQuery 对象插入到集合中每个元素的末尾 匹配的元素。

【讨论】:

    【解决方案2】:

    是的,谢谢,此代码有效。我也有两个小括号而不是一个小错误。在这一行 $.each(data.NewsSources, function(i, f)

    <html>
    <head>
    <script type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
    </script>
    
    <script>
    
    $(function() {
    
    
    
    $.getJSON('https://ws.365scores.com/Data/news/?newsitems=101640575', function(data) {
    $.each(data.NewsSources, function(i, f) {
      var vid=f.Name;
       $("#userdata").append(vid);
    });
    
    });
    
    });
    </script>
    </head>
    
     <body>
    
    
    <div id= "userdata">
    <h1>This is a name</h1>
    </div>
    
    
    </body> 
     </html>    
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2023-03-11
      • 2021-09-12
      • 2017-10-27
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多