如何使用Ajax动态更新JSON-LD脚本?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用Ajax动态更新JSON-LD脚本?相关的知识,希望对你有一定的参考价值。
我有JSON-LD,如ratingValue
和ratingCount
来自后端,但我想通过Ajax调用从UI进行,并在aggregateRating
中更新它。
但是当打开页面源时,它显示来自后端的数据,但是当我执行console.log()
时,它显示了预期的值,但它没有在页面源中更新。
有什么方法可以从UI端进行吗?
<script type="application/ld+json"> {
"@context": "http://schema.org/",
"@type": "Product",
"name": "Phone",
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "4.5",
"ratingCount": "80"
},
"offers": {
"@type": "AggregateOffer",
"lowPrice": "5",
"highPrice": "10",
"priceCurrency": "USD",
"availability": "http://schema.org/InStock"
}
}
</script>
(function () {
var id = $ {
prdId
};
var response = "";
$.ajax({
url: url;
dataType: "jsonp",
data: {
pid: id,
_method: "GET",
t: new Date().getTime()
},
timeout: 20000,
xhrFields: {
withCredentials: true
},
type: "get",
success: function (json) {
if (json.success == true) {
response = json.data;
//call api
structureData(response);
} else {
response = "error";
}
}
});
function structureData(resp) {
var json = document.querySelector('script[type="application/ld+json"]').textContent;
json = JSON.parse(json);
json["aggregateRating"] = {
"@type": "AggregateRating",
"ratingValue": resp.averageScore,
"reviewCount": resp.averageScore
}
var jso = JSON.stringify(json);
document.querySelector('script[type="application/ld+json"]').textContent = jso;
}
}
答案
你绝对可以动态地更新JSON-LD,这是一个更粗略的例子 - 但你可以运行代码片段并看到它正常工作。我通过this SO question找到了关于大致相同主题的代码,但修改它以更好地匹配您的示例:
let jsonLdScript = document.querySelector('script[type="application/ld+json"]');
let jsonld = JSON.parse(jsonLdScript.innerText);
document.getElementById('orig-result').textContent = jsonLdScript.innerText;
jsonld.aggregateRating.ratingValue = "5";
jsonld.aggregateRating.ratingCount = "95";
let newJson = JSON.stringify(jsonld);
jsonLdScript.innerhtml = newJson;
document.getElementById('result').textContent = jsonLdScript.innerText;
<html>
<head>
<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "Product",
"name": "Phone",
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "4.5",
"ratingCount": "80"
},
"offers": {
"@type": "AggregateOffer",
"lowPrice": "5",
"highPrice": "10",
"priceCurrency": "USD",
"availability": "http://schema.org/InStock"
}
}
</script>
</head>
<body>
<p>Original Output JSON-LD: <br /><strong id="orig-result"></strong></p>
<p>New Output JSON-LD: <br /><strong id="result"></strong></p>
</body>
</html>
以上是关于如何使用Ajax动态更新JSON-LD脚本?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用JSON-LD创建SiteNavigationElement?