【发布时间】:2015-05-22 13:28:42
【问题描述】:
使用 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 及其内容存储在本地机器上,GET、POST 或成功(在这里没有意义;
$.cookie("userFavourites")是您需要/关心的全部内容
标签: javascript jquery json angularjs cookies