使用 AngularJS,我了解如何使用 AJAX 请求获取 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");
}
}
信息添加到 cookie 中就很好,一旦我在 cookie 中添加了一些公园,当我 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)
我还尝试按照本文档(https://docs.angularjs.org/api/ng/service/ $http#jsonp)将 $http.get 更改为 $http.jsonp,但我没有任何运气。
感谢任何帮助:)
最佳答案
Cookie 是浏览器中的本地元素,而不是服务器上的元素,因此您无需使用 ajax 来获取它,而是可以简单地在 javascript 中打印其值
console.log($cookies.get('myFavoriteCookie'));
更多详情here
关于javascript - AngularJS:访问存储在 jQuery cookie 中的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29144493/