[英]How do I update data embedded in the HTML script tag?
I have a simple html page with Json-ld data embedded in the script tag. 我有一个简单的html页面,其中在script标签中嵌入了Json-ld数据。
How do I update this data on the submit of a form? 如何在提交表单时更新此数据?
Here is some of the code of the page (data + load function). 这是页面的一些代码(数据+加载功能)。 What I'm missing is the saveData function that updates the data embedded in the script section.
我缺少的是saveData函数,该函数可更新脚本部分中嵌入的数据。
Thank you, 谢谢,
<script id="person" type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Person",
"givenName": "Marco",
"familyName": "Van Basten"
}
</script>
<script>
function loadData() {
var person = document.getElementById("person").textContent;
var jsonld = JSON.parse(person);
document.getElementById("givenName").value = jsonld.givenName;
document.getElementById("familyName").value = jsonld.familyName;
}
The following code snippet is for example only , but should show you how to update your script object with the JSON string using JSON.stringify
. 以下代码段仅作为示例 ,但应向您展示如何使用
JSON.stringify
使用JSON字符串更新脚本对象。
person.innerHTML = JSON.stringify(jsonld);
Load the original by using Load. 通过使用加载来加载原件。 Change the values then Save and Load again.
更改值,然后再次保存并加载。 Use the browser developer tools to watch the values of the DOM.
使用浏览器开发人员工具观察DOM的值。
function loadData(e) { var person = document.getElementById("person"); var jsonld = JSON.parse(person.textContent); console.log(jsonld.givenName, jsonld); document.getElementById("givenName").value = jsonld.givenName; document.getElementById("familyName").value = jsonld.familyName; } function saveData(e) { console.log('event', e); var person = document.getElementById("person"); var jsonld = JSON.parse(person.textContent); jsonld.givenName =document.getElementById("givenName").value; jsonld.familyName =document.getElementById("familyName").value; //person.innerHTML = JSON.stringify(jsonld); person.textContent = JSON.stringify(jsonld); } document.getElementById("saveButton").addEventListener('click', saveData); document.getElementById("loadButton").addEventListener('click',loadData);
<script id="person" type="application/ld+json"> { "@context": "http://schema.org", "@type": "Person", "givenName": "Marco", "familyName": "Van Basten" } </script> <form> <input type="text" id="givenName" /> <input type="text" id="familyName" /> </form> <button id="loadButton">Load</button> <button id="saveButton">Save</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.