使用angular$http和django-urlpatters来获得json文件
use angular $http with django urlpatterns to get a json file
我要做的是向django-url模式发送一个$http GET请求,并返回一个.json文件。我可以使用urlpatters返回文件而不是视图吗?
这可能吗?
目前表单/数据返回500
testModule.js
angular.module('mod1', ['mod2'])
.controller('resorcesCtrl', ['mod2Factory',
function(mod2Factory) {
mod2Factory.getJSON();
}
]);
angular.module('mod2', [])
.factory('mod2Factory', [ '$http',
function($http) {
var getJSON = function() {
return $http({
url: "/form/data",
method: "GET"
})
}
return {
getJSON:getJSON
};
}
])
urls.py
url(r'^form/data', 'myApp.views.getJSON', name='getJSON'),
views.py
def getJSON(request):
context = {
"json": json
}
return render(request, '', context)
从Django 1.7开始,有一个名为JsonResponse的新响应对象。
你的观点可以很简单:
from django.http import JsonResponse
def getJSON(request):
# context is a Python dict.
context = {
"key": "value",
"other_key": 365,
}
return JsonResponse(context)
context
必须是有效的JSON可序列化对象。有关JsonResponse
的更多详细信息,请参阅文档。如果您在序列化方面有任何问题,可以将自己的编码器传递给JsonResponse
来处理自定义数据类型,请阅读更多信息。
我更喜欢使用类似的函数
import json
from django.http import HttpResponse
def json_responder(**kwargs):
return HttpResponse(json.dumps(kwargs), content_type="application/json")
def yourview(request):
return json_responder(type='error', msg='a message")
并且可以在每个django版本上使用
相关文章:
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 不显示带有本地json文件数据的谷歌地图脚本
- 可以't使用Appcelerator将JSON文件解析为JavaScript中的TableView
- 加载两个具有相同父密钥名称的json文件
- 使用JSON文件中的变量(字符串)填充文本区域
- 动态显示JSON文件内容
- 正在尝试将JSON文件放入JS数组
- 如何检查Json文件更新,如果更新了,则用更新的数据刷新我的页面
- 单击按钮更改加载到表中的JSON文件
- 处理一个JSON文件;完全相同的副本不是
- 在Javascript中加载JSON文件
- 使用Bootstrap将JSON文件加载到表中
- Angular 2:在本地.json文件上找不到文件
- JSON-从浏览器向外部服务器发送哪些http头JSON文件
- 如何获取d3.js中json文件中具有特定值的总行数
- 如何在dojo应用程序构建概要文件中加载json文件
- jQuery UI使用json文件自动完成
- 通过Azure存储以HTML形式获取JSON文件
- ngResource没有'从JSON文件解析HTML时不起作用