[英]Django - How do I properly send a list from template to AJAX to view?
每当用户单击按钮时,我都试图向服务器发出AJAX获取请求。 有两种按钮。 一个按钮可触发所有列出的摄像机的所有警报,每个单独的摄像机都有一个按钮。
我的问题是我试图将AJAX的词典列表返回到视图。 jQuery将对象视为字符串,因此从技术上讲,我猜它已经是JSON格式。 当我将其发送到视图时,视图将其视为Querydict,而当我尝试对其进行索引时,它仅返回字符串的单数字符。 当我尝试在views.py
调用json.loads(cameras)
时,抛出一个错误:
json.decoder.JSONDecodeError:期望属性名称用双引号引起来:第1行第3列(字符2)`
我知道这可能与前端处理变量有关,但是我不确定如何解决此问题。 我最初是否应该将变量从视图传递到模板? 我是否将变量从模板正确传递给JQuery? 我在JQuery中处理变量不正确吗? 还是我只是在做一些错误的看法?
这是用户看到的
views.py
def trigger_sirens(request):
# Retrieve the list of dictionaries
cameras = request.GET.get('cameras')
print(type(cameras)) # ==> <class 'str'>
print(cameras) # ==> [{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}]
print(cameras[0]) # ==> [
# Manipulate data
return JsonResponse({'success': True}, status = 200) # This is just a placeholder for now
siren_search.html
<!-- These buttons are wrapped in forms because this is how I built it first
without using javascript, but now I'm trying to implement javascript functionality -->
<!-- A button to trigger all the listed -->
<form id="trigger-all-form" action="{% url 'camera_search:siren_search' %}" method="GET">
<button id="trigger-all-btn" name="pulse-all-sirens" type="submit"
class="btn siren-btn btn-lg btn-block js-trigger-all-sirens-btn"
value="{{ cameras }}">
Trigger all sirens at {{ term }}
</button>
</form>
<!-- A button to trigger only one siren -->
<form id="{{ camera.asset_name }}-siren-form"
action="{% url 'camera_search:siren_search' %}" method="GET">
<button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn"
name="button-big-submit" class="btn siren-btn" value="{{ camera.asset_name }}">
{{ camera.asset_name }}
</button>
</form>
custom.js
function buttonAjaxCall(buttonObject) {
var camerasToTrigger = buttonObject.attr('value');
console.log(jQuery.type(camerasToTrigger)) // string
console.log(camerasToTrigger) // [{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}]
console.log(jQuery.type(JSON.stringify(camerasToTrigger))) // string
console.log(JSON.stringify(camerasToTrigger)) // "[{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}]"
if (buttonObject.hasClass('js-trigger-all-sirens-btn')) {
// Convert data this way, still not sure how
}
else {
// Convert data for one button, still not sure how
}
$.ajax({
url: 'siren/',
type: 'GET',
data: {
'cameras': camerasToTrigger,
},
dataType: 'json',
success: function (response) {
console.log('Success: ', response)
},
error: function (response) {
console.log('Error: ', response)
}
});
}
编辑根据Daniel的评论,我已经在views.py
中添加了将代码传递到模板的代码。
# deployed is a list of dictionaries
context = {
'cameras': sorted(deployed, key=lambda camera: (camera['site_id'] == 'N/A', camera['site_id'])),
'term': term
}
return render(request, 'siren_search.html', context)
这对我有用。 我的问题是Javascript中的cameraToTrigger字符串具有单引号字符'
,并且这些字符必须为双引号"
,以便将该字符串转换为JSON。
# views.py
def trigger_sirens(request):
# Retrieve the list of dictionaries in JSON format
cameras = request.POST.get('cameras', None)
# Read in the JSON object if it exists
if cameras_json is not None:
cameras = json.loads(cameras_json)
else:
return JsonResponse({'success': False}, status = 400)
return JsonResponse({'success': True}, status = 200)
// custom.js
function buttonAjaxCall(buttonObject) {
var camerasToTrigger = buttonObject.attr('value');
var data = {
// Make sure the list is JSON
'cameras': camerasToTrigger.replace(/'/g, '"');
}
$.ajax({
url: 'siren/',
type: 'GET',
data: data,
dataType: 'json',
success: function (response) {
console.log('Success: ', response)
},
error: function (response) {
console.log('Error: ', response)
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.