application / ld + json和javascript数据交换

时间:2016-07-18 13:08:44

标签: javascript jquery json-ld

我有一些构建名为myList[]的数组的jQuery代码。这个数组出现在控制台中,如下所示:["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?提前谢谢!

1 个答案:

答案 0 :(得分:8)

请试试这个:

<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,这是单数。 (谢谢@AlexKudryashev)。