我需要将一些数据从html
文件发送到django
进行处理,然后使用ajax
返回
但是响应将返回状态为= 0的ajax调用中的错误回调
这是ajax代码,我已经尝试了两个带注释的URL
function snapshot() {
ctx.drawImage(video, 0,0, canvas.width, canvas.height);
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
console.log(imageData)
//url:"{% url 'blind:getcaption' %}",
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/blind/ajax/getcaption/',
//url: /ajax/getcaption/
data: {
'img': imageData
},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function(request, status, error){
console.log(request, " " ,status, " ", error)
}
});
}
这是views.py
def getcaption(request):
img = request.GET.get('img', None)
data = {'caption': "This caption for test"}
return JsonResponse(data)
还有urls.py
app_name = 'blind'
urlpatterns = [
path('', views.index, name='index'),
url(r'^ajax/getcaption/$', views.getcaption, name='getcaption'),
]
但是当我输入url时,点击url:'http://127.0.0.1:8000/blind/ajax/getcaption/
可以让我在chrome中重新查看json对象
答案 0 :(得分:0)
首先,您可以如下所示在ajax调用中编写url
,然后解析您获得成功的JSON
。
function snapshot() {
ctx.drawImage(video, 0,0, canvas.width, canvas.height);
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
console.log(imageData)
//url:"{% url 'blind:getcaption' %}",
$.ajax({
type: 'GET',
url : '{% url "getcaption" %}',
data: {
'img': imageData
},
dataType: 'json',
success: function (data) {
console.log(JSON.parse(data));
},
error: function(request, status, error){
console.log(request, " " ,status, " ", error)
}
});
}
然后更改视图,将字典转储到json对象,然后返回json响应:
def getcaption(request):
img = request.GET.get('img', None)
data = {'caption': "This caption for test"}
return JsonResponse(data)