2017-02-26 153 views
0

我正在构建一个应用程序,用于从JSON文件中添加和删除项目。 我遇到了以下问题:当我删除一个项目时,它会反映在前端(该项目消失),但需要几个硬页面重新加载让应用程序读取我生成的新JSON文件PHP文件而不是缓存的文件。在AngularJS中处理缓存和更新的JSON文件

如果我只是重新加载一次,它只会读取缓存中的JSON文件,这并不反映所做的更改。

有没有什么办法可以直接在AngularJS中处理这个问题?

这里是我的角码:

$scope.remove = function(array, index){ 
    if($scope.totsselected){ 
     array.splice(index, 1); 
     $http.post("deleteall.php", { 
      data : array 
     }) 
     .then(function(data, status, headers, config) { 
     $http.get('data/all.json') 
      .then(function (response) { 
       $scope.productesgenerals = response.data; 
       console.log($scope.productesgenerals); 
      }).catch(function (error) { 
     }); 
     }); 
    } 
)}; 

我的PHP代码:

<?php 

$contentType = explode(';', $_SERVER['CONTENT_TYPE']); 

$rawBody = file_get_contents("php://input"); // Read body 
$data = json_decode($rawBody); // Then decode it 
$all = $data->data; 

$jsonData = json_encode($all); 
file_put_contents('data/all.json', $jsonData); 
?> 

回答

1

这听起来像你有$ HTTP缓存打开。尝试禁用它为此请求

$http.get('data/all.json', {cache: false}) 

https://docs.angularjs.org/api/ng/service/ $ HTTP缓存#

如果不工作(它仍缓存),那么它听起来像服务器端缓存。你可以通过发送一个唯一的查询字符串来破解它。

$http.get('data/all.json?_=' + Date.now(), {cache: false}) 

这将使每个请求一个唯一的请求,并应防止服务器端缓存。

需要注意的是,由于您忽略了缓存,因此您将失去缓存的所有性能优势。