我有文件JSON数据,我在UI上显示,以及用户可以从中更新数据的表单。如何使用用户在表单上输入的值更新JSON数据,并在提交后在UI上呈现它。
//Html code
<div id="myModal" class="modal">
<!-- Add movie Modal content -->
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<form name="submitmovie" onsubmit="addMov()">
<label>Enter Movie Name</label>
<input type="text" name="movie-name" id="mnane" placeholder="enter movie name">
<label>Year</label>
<input type ="number" name="movie-year" id="myear" placeholder="movie-year">
<label>Poster Url</label>
<input type ="url" name="movie-poster" id="mposter" placeholder="movie-poster-url">
<button class="addMovie" type = "submit">Submit</button>
</form>
</div>
</div>
<script type="text/javascript">
function addMov(){
var name = document.getElementById("mnane").value;
var year = document.getElementById("myear").value;
var url = document.getElementById("mposter").value;
console.log(name,year,url);
// add();
movieList.push({
"name":name,
"year":year,
"url":url
});
renderMovieCards();
}
</script>
要对JSON文件执行更新,您需要一个后端或某些第三方产品,其作用类似于后端,例如。火力地堡。
如果我们只在本地谈话(页面刷新时仍然存在更改),您可以:
<div id="myModal" class="modal">
<!-- Add movie Modal content -->
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<form name="submitmovie" onsubmit="addMov()">
<label>Enter Movie Name</label>
<input type="text" name="movie-name" id="mnane" placeholder="enter movie name">
<label>Year</label>
<input type="number" name="movie-year" id="myear" placeholder="movie-year">
<label>Poster Url</label>
<input type="url" name="movie-poster" id="mposter" placeholder="movie-poster-url">
<button class="addMovie" type="submit">Submit</button>
</form>
</div>
</div>
<script type="text/javascript">
// persist mechanics
// on app load try to load data from localStorage
const movieList = localStorage.getItem('movieList');
// if it's there assign it to moveList, else leave it as is (with json data)
if (movieListLocalStorage) {
movieListLocalStorage = JSON.parse(movieListLocalStorage);
}
function addMov() {
var name = document.getElementById("mnane").value;
var year = document.getElementById("myear").value;
var url = document.getElementById("mposter").value;
console.log(name, year, url);
// add();
movieList.push({
"name": name,
"year": year,
"url": url
});
// since you are using movieList i am assuming it has predefined json data assigned
// persist updated data within localStorage
localStorage.setItem('movieList', JSON.stringify(movieList))
// pass updated data to render function
renderMovieCards(movieList);
}
</script>