不能打电话的Django与angularjs JSON视图 [英] can't call django json view with angularjs
问题描述
我是新的Django和也angularjs。
我想要使用Django的REST API和angularjs的前端视图。
我有一个返回JSON响应Django视图:
类MyView的(查看): DEF得到(个体经营,要求):
数据= serializers.serialize('JSON',MyModel.objects.order_by('名'))
返回的Htt presponse(数据,MIME类型=应用/ JSON) DEF选项(个体经营,要求):
响应= Htt的presponse()
响应['允许'] =''。加入(['得到','后','放','删除','选择'])
返回响应
呼叫
的http://本地主机:8000 / MyApp的/ MyView的
我得到正确的JSON响应
如果在angularjs控制器(controllers.js)我尝试调用像这样的观点:
angular.module('myApp.controllers',[])。
控制器('MyCtrl',['$范围,$ HTTP',函数($范围,$ HTTP){
$ scope.test =霍拉;
删除$ http.defaults.headers.common ['X-要求-随着'];
$ http.get(的http://本地主机:8000 / MyApp的/ MyView的').success(功能(数据){
$ scope.results =数据;
的console.log(数据);
})错误(功能(数据,状态){
$ scope.data = ||数据请求失败;
$ scope.status =状态;
的console.log(数据);
});
}]);
测试值是否正确打印模板
在Django登录我有:GET / MyApp的/ MyView的/ HTTP / 1.1200 853
但在角我不获取任何数据。如果我把一个破发点中的错误方法,我有空数据和状态= 0。
任何提示?
我这么想吗?
$ http.get(的http://本地主机:8000 / MyApp的/ MyView的/').success(函数(数据)
URL需要降尾随/,然后追加以.json。像这样:
$ http.get(的http://本地主机:8000 / MyApp的/ myview.json').success(功能(数据)
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?
$http.get('http://localhost:8000/myapp/myview/').success(function(data)
The URL needs to drop the trailing /, then append .json. Like so:
$http.get('http://localhost:8000/myapp/myview.json').success(function(data)
这篇关于不能打电话的Django与angularjs JSON视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!