我的WP博客页面中有结构化的数据(json)。我需要为用户展示一些来自json的数据。
Json看起来是这样的。
<script data-snippet_id="" type="application/ld+json"> {
"sku":"",
"mpn":"",
"image":"",
"name":"",
"description":"",
"review": {
"publisher": {
"url": "", "name": "", "@context": "", "@type": ""
}
,
"dateModified":"2020-04-08T19:08:17+03:00",
"author":[ {
"name": "", "@context": "http:\/\/schema.org", "@type": "Person"
}
],
"description":"",
"dateCreated":"",
"reviewRating": {
"ratingValue": "4", "@context": "http:\/\/schema.org", "@type": "Rating"
}
,
"@context":"http:\/\/schema.org",
"@type":"Review"
}
,
"@context":"http:\/\/schema.org",
"@type":"Product"}</script>
我需要通过jquery来获取ratingValue,来向用户展示。
我试着使用函数getJSON,但它对我不起作用。
$(document).ready(function() {
$.getJSON('post', function(emp) {
$('#display').html('<p> ratingValue : ' + emp.ratingValue + '</p>');
});
});
如果JSON被PHP输出到页面中,变成了一个 "JSON"。<script>
标签,那么你不需要使用AJAX来检索它。您可以简单地检索 text()
该要素的和 JSON.parse()
它。
还注意到 ratingValue
嵌套在 review.reviewRating
对象,所以获取值的方法需要稍微改变。试试这个。
let json = JSON.parse($('script[data-snippet_id]').text());
$('#display').html('<p>ratingValue: ' + json.review.reviewRating.ratingValue + '</p>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script data-snippet_id="snip-5e99a87c31435" type="application/ld+json">{"sku":"","mpn":"","image":"","name":"","description":"","review":{"publisher":{"url":"","name":"","@context":"","@type":""},"dateModified":"2020-04-08T19:08:17+03:00","author":[{"name":"","@context":"http://schema.org","@type":"Person"}],"description":"","dateCreated":"","reviewRating":{"ratingValue":"4","@context":"http://schema.org","@type":"Rating"},"@context":"http://schema.org","@type":"Review"},"@context":"http://schema.org","@type":"Product"}</script>
<div id="display"></div>