简体   繁体   English

如何使用Ajax动态更新JSON-LD脚本?

[英]How can I dynamically update the JSON-LD script with Ajax?

I have JSON-LD as shown, where ratingValue and ratingCount are coming from backend, but I want do it from UI through Ajax call and update it in the aggregateRating . 我有如图所示,其中JSON-LD ratingValueratingCount从后端来了,但我想从UI做通过Ajax调用,并在更新aggregateRating

But when opened page source it is showing data coming from the backend, but when I do console.log() it is showing the value expected but it is not updated in page source. 但是,当打开页面源时,它将显示来自后端的数据,但是当我执行console.log()它将显示预期的值,但不会在页面源中更新。

Is there any way possibly do it from the UI side? 从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;

    }
}

You can definitely update JSON-LD dynamically, this is a more crude example - but you can run the code snippet and see it working. 您绝对可以动态更新JSON-LD,这是一个更原始的示例-但是您可以运行代码片段并查看其工作原理。 I found the code through this SO question about roughly the same topic but modified it to match your example better: 我通过这个大致相同主题的问题找到了代码,但对其进行了修改以更好地匹配您的示例:

 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> 

How are you testing? 您如何测试? A few things to keep in mind: 请记住以下几点:

  • Obviously the raw page DOM won't be modified 显然,原始页面DOM不会被修改
  • You should see the changes in dev tools 您应该看到开发工具中的更改
  • If you're using Googles Structured Data Tool , and the original JSON is parsed before your function updates it, I'd wager Google won't catch the change. 如果您使用的是Google的结构化数据工具 ,并且原始JSON在您的函数更新之前已解析,那么我敢打赌Google不会抓住这一变化。
  • If you're using querySelector, might want to confirm that the JSON-LD you intend to modify is the first instance of JSON-LD on the page. 如果使用的是querySelector,则可能要确认要修改的JSON-LD是页面上JSON-LD的第一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM