从js发送复选框数组到Django视图 [英] sending checkbox array from js to django views
问题描述
我对如何通过Ajax或Json做到这一点感到困惑,但是如何将选择数组(curCheck)单击发送到Django视图并将其作为python数组接收
I'm confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array
javascript
javascript
document.getElementById('results').addEventListener('click', function(){
html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>'
var checkElements = document.getElementsByClassName('ch');
for(var i =0; i< curname.length; i++){
if (checkElements[i].checked) {
var curChecked = curname[i];
var JsonArr = JSON.stringify(curChecked);
postcurChecked(JsonArr)
html_table += '<tr><td>' + curname[i] + '</td>';
}
}
document.getElementById('result_table').innerHTML = html_table;
},false;
ajax
function postsubChecked(curChecked) {
$.ajax({
"url": "http://127.0.0.1:8000/results/",
"type": "POST",
"data": {"checkbox": curChecked},
"headers": { 'X-CSRFToken': getCookie('csrftoken')}
})
}
在Django
def currencyChecked(request):
body_unicode = request.body.decode('utf-8')
body_unicode = body_unicode.replace('%22','')
print(body_unicode) json_data = json.loads(body_unicode.read())
我想看一下python数组的打印内容,看看它是否传递到了后面
I would like to see the python array print to see it is passed to the back
但我一直收到此错误: json_data = json.loads(body_unicode.read())AttributeError:'str'对象没有属性'read'
but I keep getting this error: json_data = json.loads(body_unicode.read()) AttributeError: 'str' object has no attribute 'read'
推荐答案
要获取选定的复选框值并使用ajax作为数组发送,可以使用如下的jquery:
For getting the selected checkbox values and sending as an array using ajax you can use jquery like this:
请考虑您有多个复选框和一个按钮.
consider you have multiple checkboxes and a button.
<input type="checkbox" name="imageName">
<input type="checkbox" name="imageName">
.......
<button id="deletePhoto">Delete</button>
选择多个复选框值后,单击此按钮.点击下面的jquery将会触发以选中的复选框值作为arrya.
after selecting multiple checkbox values click on this button. On clicking the below jquery will be triggered to make an arrya of selected checkbox values.
//jquery for getting the selelcted checkbox values
$(document).on("click","#deletePhoto",function(){
var favorite = [];//define array
$.each($("input[name='imageName']:checked"), function(){
favorite.push($(this).val());
});
alert("Photo Selected: " + favorite.join(", "));
if(favorite.length == 0){
alert("Select Photo to delete");
return false;
}
//ajax for deleting the multiple selelcted photos
$.ajax({type: "GET",
url: "/olx/deletePhotoFromEdit",
data:{
favorite:favorite
},
success: function(){
// put more stuff here as per your requirement
});
}
});
});
在视图中,您可以像这样获得数组:
In the view you can get the array like this:
selected_photo = request.GET.getlist('favorite[]')
这篇关于从js发送复选框数组到Django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!