2016-07-18 37 views
0

我有一些jQuery代碼構造了一個名爲myList[]的數組。這個數組像這樣出現在控制檯中:["2 items", "3items", "so on"],所以這部分進行得很順利。application/ld + json和javascript數據交換

<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?提前致謝!

+0

如果你真的想在你的頁面上放置'ld + json'標記,那麼在服務器端執行它。 Google不讀取在客戶端創建的掩模。 –

+0

@AlexKudryashev是的谷歌檢測客戶端創建標記:D –

+0

@IsmailRBOUH你可以給一個證明鏈接? –

回答

3

請試試這個:

<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)。

+0

他,謝謝你的建議!但它不工作... –

+0

我已編輯了一些問題,以顯示更多的代碼... –

+0

請檢查更新的答案! –