簡體   English   中英

application / ld + json和javascript數據交換

[英]application/ld+json and javascript data exchange

我有一些jQuery代碼構造一個名為myList[]的數組。 這個數組出現在控制台中,如下所示: ["2 items", "3items", "so on"] ,所以這部分進展順利。

<script type="text/javascript">
var myList = [];
function buld myList(){
...
}

我需要將myList[]傳遞給application/ld+json類的

<script type="application/ld+json">
{
    "@context": "http://schema.org/",
    "@type": "Recipe",
    "recipeIngredients": myList, //this one doesn't work 
}

..

如何將值從javascript傳遞給application/ld+json 提前致謝!

請試試這個:

<script id="myJSONID" type="application/ld+json"></script>

然后:

var myList = [];

function buildMyList() {
    return ["2 items", "3items", "so on"];
}

$("#myJSONID").text(function() {
    return JSON.stringify({
        "@context": "http://schema.org/",
        "@type": "Recipe",
        "recipeIngredient": buildMyList()
    });
});

要么:

<script type="text/javascript">
  var myList = [];    
  function buildMyList() {
      return ["2 items", "3items", "so on"];
  }

  var el = document.createElement('script');
  el.type = 'application/ld+json';

  el.text = JSON.stringify({
        "@context": "http://schema.org/",
        "@type": "Recipe",
        "recipeIngredient": buildMyList()
    });

  document.querySelector('body').appendChild(el);
</script>

演示: https //jsfiddle.net/iRbouh/9po7dtg4/

注意:請確保將recipeIngredients更改為recipeIngredient ,singular。 (謝謝@AlexKudryashev)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM