2015-03-19 56 views
0

使用AngularJS,我了解如何使用AJAX请求获取JSON数据。AngularJS:访问存储在jQuery cookie中的json数据

$http.get('data/parks.json').success(function(data){ 
     $scope.parks = data; 
    }); 

不过,我目前存储JSON信息的jQuery的cookie中的服务器,我需要使用AJAX请求访问文档中反对:这是如下完成。

数据使用下面的代码存储在cookie中:

// Add the selected park to the users favourite list 
$scope.addFavourite=function(id){ 

    // If user has cookie named userFavourites 
    if(typeof $.cookie("userFavourites") != "undefined"){ 

     // Turn the cookie data into readable JSON 
     var favourites = $.parseJSON($.cookie("userFavourites")); 

     // Filter through the the results of the JSON object and check to see if the result is equal to the selected parks ID 
     var repeated = favourites.filter(function(a){ 
      return a.id == id 
     }).length; 

     // If park is not in the list, add it to the list 
     if(!repeated){ 
      favourites.push({"id":id}); 
      if($.cookie("userFavourites", JSON.stringify(favourites))){ 
       alertify.success("Successfully added park to favourites"); 
      } 
      else alertify.eror("Failed to store park in cookie"); 
     } 

     // Inform the user that the park is already a favourite 
     else alertify.error("Oops... This park is already in your favourites list!"); 

    } 
    else{ 
     var favourites = [{ "id":id }];   
     $.cookie("userFavourites", JSON.stringify(favourites)); 
     alertify.success("Successfully added park to favourites"); 
    } 
} 

的信息添加到饼干就好了,一旦我增加了一些公园到饼干,当我CONSOLE.LOG我得到它:

[{"id":1},{"id":2}] 

我的问题是,当我想获取内AngularJS使用AJAX的数据,我不知道如何从一个cookie获取JSON数据从文件夹结构中的文件反对。

我曾尝试以下,但它只能在控制台中返回一个错误:

$scope.listFavourites=function(){ 

    if(typeof $.cookie("userFavourites") != "undefined"){ 

     $http.get($.cookie("userFavourites")).success(function(data){ 

      $scope.favourites = data; 
      $scope.totalFavourites = data.length; 

     }); 

    } 
    else{ 
     $scope.favourites = "Empty"; 
    } 

    console.log($scope.favourites); 

} 

错误:

GET http://www.example.com/angularjs/[%7B%22id%22:1%7D,%7B%22id%22:2%7D] 404 (Not Found) 

我也试图改变$ http.get至$ HTTP。 jsonp遵循这个文档(https://docs.angularjs.org/api/ng/service/ $ http#jsonp),但我没有任何运气。

任何帮助表示赞赏:)

+0

饼干和它的内容存储在本地计算机上,GET,POST或成功(使得这里毫无意义;'$ .cookie(“userFavourites”)'是你应该需要大约/护理 – birdspider 2015-03-19 12:27:31

回答

1

的Cookie是在浏览器中,而不是在服务器上的本地元素,这样你就不会用ajax获取它,而不是你可以简单地打印出它的价值在JavaScript

console.log($cookies.get('myFavoriteCookie')); 

详情here

+0

当然是,我为什么不提那个。经典的情绪阻挡在一分钟!感谢您的意见。我会upvote你的答案,但没有足够的分数:/ – DannyDanDan 2015-03-19 12:30:08