Ale*_*alo 10 json structured-data parse-platform json-ld
我正在开发一个网站,我想将结构化数据添加到详细页面.问题是我需要在知道要添加到JSON-LD脚本的内容之前请求数据.
我使用Parse作为后端.我还试图寻找有关如何实现这一目标的教程,但似乎无法动态添加JSON-LD.
我真的希望有人可以帮助我!:)
编辑:
在DOM准备好之后,我需要在JSON-LD中添加数据的响应.这种情况下的模式是什么?
我有一个项目列表,当点击其中一个项目时,我必须打开一个我必须先加载的详细信息页面,但是在加载内容之后我想通过JSON-LD提供结构化数据.
我刚开始,我很难解决这个问题.
编辑2:
这是我的实际实现:
在HTML中:
<body>
// my html page code
...
<script type="text/javascript">
loadDetailPageContent();
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
在JS中:
function loadDetailPageContent() {
// Calling the method here is too early because I don't have info
//writeData();
createDetailPage();
}
function createDetailPage() {
var recipe = Parse.Object.extend("Recipe");
var query = new Parse.Query(recipe);
query.equalTo("objectId", myId);
query.first({
success: function(result) {
// Calling the method here would be perfect
writeData();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
function writeData() {
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify({
"@context": "http://schema.org",
"@type": "Recipe",
"name": "My recipe name"
});
document.querySelector('head').appendChild(el);
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,方法writeData()在两个地方被调用.如果我在开始时立即调用它,则没有问题,使用Google结构化数据测试工具,我能够跟踪我需要的结构化数据.问题在于,此时我没有创建结构化数据的信息,因为我需要等待Parse的响应.
当我在成功回调中调用方法时,测试工具不再能够检索数据:(
Mou*_*sey 13
http://jsfiddle.net/c725wcn9/2/embedded
您需要检查DOM以检查其是否有效.需要Jquery.
$(document).ready(function(){
var el = document.createElement('script');
el.type = 'application/ld+json';
el.text = JSON.stringify({ "@context": "http://schema.org", "@type": "Recipe", "name": "My recipe name" });
document.querySelector('head').appendChild(el);
});
Run Code Online (Sandbox Code Playgroud)
你的代码中包含了变量名script,但附加变量el的<head>替代.还删除了JSON字符串中的新行字符,该字符串已使用JSON-LD playground进行检查.