gpt4 book ai didi

javascript - 将 angular $http 与 django urlpatterns 一起使用以获取 json 文件

转载 作者:行者123 更新时间:2023-11-30 12:26:21 29 4
gpt4 key购买 nike

我想做的是向 django url 模式发送一个 $http GET 请求并返回一个 .json 文件。我可以使用 urlpatterns 返回文件而不是 View 吗?

这可能吗?

当前表单/数据返回 500

测试模块.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
};
}
])

网址.py

url(r'^form/data', 'myApp.views.getJSON', name='getJSON'),

View .py

def getJSON(request):
context = {
"json": json
}
return render(request, '', context)

最佳答案

从 Django 1.7 开始,有一个名为 JsonResponse 的新响应对象。 .

您的 View 可以很简单:

from django.http import JsonResponse

def getJSON(request):
# context is a Python dict.
context = {
"key": "value",
"other_key": 365,
}
return JsonResponse(context)

context 必须是有效的 JSON 可序列化对象。参见 the docs有关 JsonResponse 的更多详细信息。如果您在序列化方面遇到任何问题,您可以将自己的编码器传递给 JsonResponse 来处理自定义数据类型,read more .

关于javascript - 将 angular $http 与 django urlpatterns 一起使用以获取 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29241522/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com