简体   繁体   中英

How to update json file in AngularJS

I want to update the existing json file in AngularJS

JSON file:

 {  
    "text1": "Click here to edit!",
    "text2": "Click here to edit!",
    "text3": "Click here to edit!",
    "text4": "Click here to edit!"  
}

I want to update this JSON file as:

text1: "Abc"

and save this changes in JSON file

You can not update a json file without using a server-side language like PHP or python. Basically it is security compliance. For more understanding kindly go through https://docs.angularjs.org/guide/security https://docs.angularjs.org/api/ng/directive/ngCsp and https://developer.mozilla.org/en-US/docs/Web/Security/CSP

Imagine you have getjson.php and savejson.php in the server which work exactly as their names suggest.

Now use $http service of Angular to retrieve your json from the server.

$http.get("getjson.php").then(function(response){

     $scope.myJsonObject = response.data;

     //Your json becomes JS object here. Change it the way you want
     $scope.myJsonObject.text1 = "Abc"; 

});

Use $http service again to send your json back to the server.

$http({
           method: "post",
           url: "savejson.php",
           data: $scope.myJsonObject,
           headers: { 'Content-Type': 'application/json; charset=utf-8' }
});

This is the basic. Please note that you need to do your php part to save/load your json file. Also you should handle errors of the $http service.

Please see how $http service and promises work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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