Jquery和Django多个复选框 [英] Jquery and Django multiple checkbox
问题描述
我有一个jquery函数,允许我选择多个复选框并创建一个字符串如下:
function getSelectedVals ){
var tmp = [];
$(input [name ='checking'])。each(function(){
if($(this).attr('checked'))
{
checked =($(this).val());
tmp.push(checked);
}
});
var filters = tmp.join(',');
alert(filters)
返回过滤器;
}
然后我调用一个django视图函数并传递如下的字符串: p>
selected = getSelectedVals();
var myurl =/ bills / delete /?id =+ selected;
$ .ajax({
type:GET,
url:myurl,
data:selected,
cache:false
});
在服务器上,我有一个删除视图函数,迭代复选框值并操作列表。 / p>
def delete(request):
全局myarray
idx = request.GET [u'id']
listidx = idx.split(',')
在listidx中为l:
value = myarray [int(l)]
myarray.remove(value)
返回HttpResponse(/ bill / jqtut /)
问题是在服务器上的所有索引我发送的GET字符串没有被处理,只有一半是。
请帮助我!感谢
从我所看到的,你会这样做。您应该在所有复选框上设置相同的名称。我不知道你为什么通过GET发送它,我建议通过POST发送它。
<输入类型=checkboxname =vehiclevalue =Bike/>
< input type =checkboxname =vehiclevalue =Car/>
< input type =checkboxname =vehiclevalue =Airplane/>
然后,在您的视图中使用getlist()方法:
def delete(request):
values = request.POST.getlist(u'vehicle')
#处理到这里。但是无论如何,除非你真的需要做自定义的东西(不过特殊情况不是特别的,不能破坏的)规则;),使用Django表单。已经有一个复选框列表OOTB。我不知道你为什么甚至在这种情况下考虑使用JavaScript。
I am a beginner in jquery so please bear with me.
I have a jquery function that allows me to select multiple checkboxes and create a string as follows:
function getSelectedVals(){
var tmp =[];
$("input[name='checks']").each(function() {
if ($(this).attr('checked'))
{
checked = ($(this).val());
tmp.push(checked);
}
});
var filters = tmp.join(',');
alert(filters)
return filters;
}
I then call a django view function and pass the string as follows:
selected = getSelectedVals();
var myurl = "/bills/delete/?id=" + selected;
$.ajax({
type: "GET",
url: myurl,
data: selected,
cache: false
});
On the server I have a delete view function that iterates over the checkbox values and manipulates a list.
def delete(request):
global myarray
idx = request.GET[u'id']
listidx = idx.split(',')
for l in listidx:
value = myarray[int(l)]
myarray.remove(value)
return HttpResponse("/bills/jqtut/")
The problem is that on the server all the indexes I am sending as the GET string are not being handled, only half are.
Please help me! Thanks
解决方案 From what I see, you do it the way around. You should set the same name on all checkboxes. I don't know why do you send it by GET, I'd suggest sending it by POST.
<input type="checkbox" name="vehicle" value="Bike" />
<input type="checkbox" name="vehicle" value="Car" />
<input type="checkbox" name="vehicle" value="Airplane" />
Then, use getlist() method in your view:
def delete(request):
values = request.POST.getlist(u'vehicle')
# Handling goes here.
But anyway, unless you really need to do custom stuff (however special cases are not special enough to break the rules ;), use Django forms. There already is a checkbox list OOTB. I'm not sure why do you even consider using JavaScript in this very case.
这篇关于Jquery和Django多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!