繁体   English   中英

使用 Javascript 或 jQuery 在 JSON(外部本地文件)中插入/更新新记录

[英]Insert/Update new Record in JSON (External Local File) with Javascript or jQuery

我仅使用客户端脚本从外部 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 文件?

谢谢你。

如果没有服务器端脚本,我不知道如何做到这一点。 但是关于客户端,除了将新的 JSON 发布到服务器并返回相同的结果(或仅使用更新的 JSON)之外,您还可以阅读:

createObjectURL()

(大多数现代浏览器都支持)

或者使用文件 API,但我不确定它是否可以远程帮助您。 您需要在本地处理它并将其发送到需要知道如何处理它的服务器。 所以无论如何,这就像在浏览器的内存中保存一个 JSON,操作它并发送它。 无需文件操作。

文件接口

您可以使用直接 AJAX 或 jQuery AJAX Post 方法。

请参阅编码器快速参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM