我只使用客户端脚本来填充外部JSON文件中的列表。
现在,我的要求是在不使用任何服务器端代码的情况下将任何记录插入/更新到同一文件。
为了从JSON填充记录,我已经完成了客户端脚本和列出JSON记录的html,如下所述:
客户端脚本:
function LoadJson(){
$(document).ready(function(){
$.ajax({
type: 'GET',
url: "js/data.json",
async: false,
dataType: "text",
error: function(e){
LoadingIssues();
},
success: function (data) {
var json = $.parseJSON(data);
var apdata = "";
console.log(json);
for(var i=0; i<json.length;i++){
apdata = "<tr>";
apdata += "<td><a onclick='SaveData();' href='javascript:;'>Edit</a></td>";
apdata += "<td>" + json[i].Name + " <strong>From:</strong> " + json[i].City + "</td>";
apdata += "</tr>";
console.log(apdata);
$("#dataJson tbody").append(apdata);
}
}
});
})
}
function LoadingIssues(){
$(".issue").html('<h3>There is some issue while loading data. Please try again later.</h3>');
}
LoadJson();
function SaveData(){
/*Code to insert/update JSON data*/
}
使用JSON数据列出的HTML:
<div class="col-lg-12">
<form>
<table class="table table-bordered">
<thead>
<tr>
<th colspan="5">Employee Details</th>
</tr>
</thead>
<tbody>
<tr>
<th>Name</th>
<td><input type="text" name="txtName" id="txtName" class="form-control"></td>
<th>City</th>
<td><input type="text" name="txtCity" id="txtCity" class="form-control"></td>
<th> <input type="button" value="Submit to JSON" class="btn btn-default" onClick="SaveData()">
</th>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
</form>
<h1>Listing</h1>
<table id="dataJson" class="table table-bordered">
<thead>
<th width="100px">Edit</th>
<th>Name</th>
</thead>
<tbody>
</tbody>
</table>
<div class="issue"></div>
</div>
有人可以建议如何使用客户端脚本来插入/更新JSON文件吗?
谢谢。
答案 0 :(得分:1)
如果没有服务器端脚本,我不知道如何做到这一点。但关于客户端,除了将新的JSON发布到服务器,并获得相同的结果(或只是使用更新的JSON),您可以阅读:
(在大多数现代浏览器中都支持)
或使用文件API,但我不确定它是否可以远程帮助您。您需要在本地处理它并将其发送到需要知道如何处理它的服务器。因此,无论如何,它就像在浏览器的内存中保存JSON,操纵它并发送它。无需文件操作。
答案 1 :(得分:0)
您可以使用直接的 AJAX 或 jQuery AJAX Post 方法。