问题
I have some jQuery code which constructs an array called myList[]
. This array appears in the console like this: ["2 items", "3items", "so on"]
, so this part goes well.
<script type="text/javascript">
var myList = [];
function buld myList(){
...
}
I need to pass myList[]
to the application/ld+json
like
<script type="application/ld+json">
{
"@context": "http://schema.org/",
"@type": "Recipe",
"recipeIngredients": myList, //this one doesn't work
}
..
How can I pass the values from javascript to the application/ld+json
? Thanks in advance!
回答1:
Please try this:
<script id="myJSONID" type="application/ld+json"></script>
Then:
var myList = [];
function buildMyList() {
return ["2 items", "3items", "so on"];
}
$("#myJSONID").text(function() {
return JSON.stringify({
"@context": "http://schema.org/",
"@type": "Recipe",
"recipeIngredient": buildMyList()
});
});
Or:
<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>
Demo: https://jsfiddle.net/iRbouh/9po7dtg4/
Note: Please make sure you change recipeIngredients
to recipeIngredient
, singular. (Thank you @AlexKudryashev).
来源:https://stackoverflow.com/questions/38437546/application-ldjson-and-javascript-data-exchange