java+ajax+修改数据,使用Ajax修改和保存JSON文件中的数据

First of all here's my .json file:

{

"ids": [1,2],

"names": ["John Richards", "Doe Williams"],

"skills": [ "Senior Software Engineer", "Junior Software Developer"]

}

And here's my ajax call to display each name from the object.

$.ajax({

dataType: "json",

url: "entries.json",

success: function(data){

for (var i = 0; i < data.names.length; i++){

console.log(data.names[i]);

}

}

});

I have a form with 3 fields and a button which I'm using to submit new data. The problem is that I can't modify that json file and submit that data.

$("#add").on("click",function(){

var url = "entries.json";

//Form input

var id = $("#empID").val();

var fullName = $("#empFullName").val();

var prof = $("#empProf").val();

var entry = { "ids":id,

"names":fullName,

"skills":prof

};

....

Ajax call for modification of the json file?!?!

What I mean by modify is to basically insert the id, fullName and prof into the corresponding field of the json and save it with the new values appended. Any insight? I'm stuck. Pulling is fine. How do I push data to the .json file? If I missed to provide anything important please let me know. I'm relatively new working with ajax.

Thanks in advance!

P.S:I've already made the project using a database if anyone's wondering.

解决方案

You cannot write to a JSON file using only JavaScript in the browser. But with JavaScript in the browser you can write Document.cookie and also write in the Window.localStorage.

Writing in the localStorage of the browser:

// Form input

var id = $("#empID").val();

var fullName = $("#empFullName").val();

var prof = $("#empProf").val();

var obj = {

"ids": id,

"names": fullName,

"skills": prof

};

localStorage.setItem('myJavaScriptObject', JSON.stringify(obj));

And than to retrieve the object, from the localStorage, you can do:

var obj = JSON.parse(localStorage.getItem('myJavaScriptObject'))

Other thing you can do is to create a service in the backend with a server-side technology like: NodeJS, Ruby on Rails, PHP, JAVA, etc... to handle the writing data in the JSON file.

And then from the browser, making a POST request that sends the form inputs data to the endpoint of your service, the data can be saved into the JSON file.

Hope this can help.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值