我有一些 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
(单数)。 (谢谢@AlexKudryashev)。
关于javascript - application/ld+json与javascript数据交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38437546/