不能用angularjs调用django json视图 [英] can't call django json view with angularjs
问题描述
我想使用Django作为前端视图的REST api和angularjs。
我有一个django视图返回一个json响应:
class MyView(View):
def get(self,request):
data = serializers.serialize ('json',MyModel.objects.order_by('name'))
return HttpResponse(data,mimetype ='application / json')
def options(self,request):
response = HttpResponse()
response ['allow'] =','。join(['get','post','put','delete','options'])
返回响应
调用
http:// localhost:8000 / myapp / myview
我得到right json response
如果在一个angularjs控制器(controllers.js)中,我尝试像这样调用该视图:
angular.module('myApp.controllers',[])。
控制器('MyCtrl',['$ scope','$ http',function($ scope,$ http){
$ scope.test =Hola;
delete $ http .defaults.headers.common ['X-Requested-With'];
$ http.get('http:// localhost:8000 / myapp / myview').success(function(data){
$ scope.results = data;
console.log(data);
})。error(function(data,status){
$ scope.data = data ||Request failed ;
$ scope.status = status;
console.log(data);
});
}]);
test值正确打印在模板中
$ b $在django日志中的b
我有:GET / myapp / myview / HTTP / 1.1200 853
但在角度我不检索任何数据。如果我在错误方法中放了一个断点,我有数据为空,状态= 0。
任何提示?
我错过了一些东西吗?
问题在于CORS。 解决方案在这里
i'm new in django and also in angularjs. I wants to use Django for a REST api and angularjs for frontend view.
I have a django view that returns a json response:
class MyView(View):
def get(self, request):
data = serializers.serialize('json', MyModel.objects.order_by('name'))
return HttpResponse(data, mimetype='application/json')
def options(self, request):
response = HttpResponse()
response['allow'] = ','.join(['get', 'post', 'put', 'delete', 'options'])
return response
calling
http://localhost:8000/myapp/myview
i get the right json response
If in an angularjs controller (controllers.js) i try to call that view like this:
angular.module('myApp.controllers', []).
controller('MyCtrl', ['$scope', '$http', function($scope, $http) {
$scope.test = "Hola";
delete $http.defaults.headers.common['X-Requested-With'];
$http.get('http://localhost:8000/myapp/myview').success(function(data) {
$scope.results = data;
console.log(data);
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
console.log(data);
});
}]);
"test" value is correctly printed in the template
in django log i have: "GET /myapp/myview/ HTTP/1.1" 200 853
but in angular i don't retrieve any data. If i put a break point in error method, i have data empty and status = 0.
Any hints? Am i missing something?
Been struggling with the same. The problem is with CORS. The solution is here
这篇关于不能用angularjs调用django json视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!