如何将此jQuery脚本转换为与JQuery.GetJson一起使用JSON对象



如何掩盖此代码以与JSON对象一起使用jQuery.getJSON()而不是基本的Java脚本对象。换句话说,我希望能够保持 代码的方式,但是使用了足够的更改,可以使用jQuery.getJSON()在另一个页面中获取JSON对象。这是我的意思。

var data = {
  shop: [{
      item: "Ps3",
      cost: "$150"
    },
    {
      item: "xbox 360",
      cost: "$140"
    },
         {
      event: "Black Friday",
      date: "4-25-2018"
    },
         {
      special_guest: "John Doe",
      time: "4:30 pm"
    }
  ]
};
$(document).ready(function() {
  var z = $('.z'); // Grab class z to toggle
  var x = $('#x');
  var output = '';
  $.each(data.shop, function(index, element) {
    for(var j in element){
      output += element[j] + '<br>' ;
    }
  });
  x.html(output);
  $("button").click(function() {
    z.toggle(); // Toggle z on button click
  });
});
h1 {
  color: gold;
}
#x {
  color: white;
  text-align: center;
}
.z {
  background-color: red;
  width: 250px;
  margin: auto;
  padding-bottom: 5px;
  display: none;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="z">
<h1>Details </h1>
<h2 id="x"></h2>
</div>
<button>Click</button>
</body>
</html>

因此,我需要找出将此JavaScript对象代码转换为JSON对象并将其放在另一个页面上。并使用jQuery.getJSON()获取此JSON对象

var data = {
    shop: [{
            "item": "Ps3",
            "cost": "$150"
        },
        {
            "item": "xbox 360",
            "cost": "$140"
        },
        {
            "event": "Black Friday",
            "date": "4-25-2018"
        },
        {
            "special_guest": "John Doe",
            "time": "4:30 pm"
        }
    ]
};

我仍然希望能够以视觉上的形式产生相同的输出,该输出使用JSON对象并使用jQuery.getjson获取该JSON对象。我知道这可能是大多数人的挑战,但我感兴趣

在代码示例中,你们愿意为我提供有关如何做到这一点的建议。我知道我的JSON代码示例的最后一件事是根据https://jsonlint.com/

不正确的。

所以我知道这一点。

调用返回JSON的API,然后将$.each循环放入回调函数中。

$(document).ready(function() {
  var z = $('.z'); // Grab class z to toggle
  var x = $('#x');
  var output = '';
  $.getJSON("url.json", function(data) {
    $.each(data.shop, function(index, element) {
      for (var j in element) {
        output += element[j] + '<br>';
      }
    });
    x.html(output);
  });
  $("button").click(function() {
    z.toggle(); // Toggle z on button click
  });
});

JSON文件应该看起来像这样:

{
    "shop": [{
            "item": "Ps3",
            "cost": "$150"
        },
        {
            "item": "xbox 360",
            "cost": "$140"
        },
        {
            "event": "Black Friday",
            "date": "4-25-2018"
        },
        {
            "special_guest": "John Doe",
            "time": "4:30 pm"
        }
    ]
}

它不应在开始时具有变量定义,或者在末尾;,这是JavaScript语句,而不是JSON数据的一部分。所有属性名称都需要在JSON中引用。

最新更新