使用AngularJS,我了解如何使用AJAX请求获取JSON数据。这样做如下:
$http.get('data/parks.json').success(function(data){
$scope.parks = data;
});
但是,我目前正在jQuery Cookie中存储JSON信息,而不是在服务器上的文档中,我需要使用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)
我还尝试将$ http.get更改为$ http.jsonp,遵循此文档(https://docs.angularjs.org/api/ng/service/ $ http#jsonp),但我没有任何运气。
感谢任何帮助:)
答案 0 :(得分:1)
Cookie是浏览器中的本地元素,而不是服务器上的元素,因此您不能使用ajax获取它,而只需在javascript中打印其值
console.log($cookies.get('myFavoriteCookie'));
更多详情here