jQuery POST不返回变量用户 [英] jQuery POST not returning variable users
问题描述
我正在尝试发布复选框的值,但无法这样做。它首先收集一个数组中的所有复选框( selected_users
,它在使用 alert
函数测试时工作正常。然后集体发送。但是我无法发布数据。我得到的错误是没有找到密钥的用户。我哪里错了?如何在jQuery插件中修改POST语句?
I am trying to post the values of checked boxes, but unable to do so. It first collects all the checked boxes in an array (selected_users
-which is working fine upon testing it with alert
function )and then sends them collectively. But I'm not able to post the data. The error that I get is Key 'users' not found in . Where i'm going wrong? how do I modify my POST statement in jQuery plugin?
View.py
def get_data(request):
def get_data(request):
if request.method == 'POST':
selected_users = request.POST['users']
return HttpResponse(selected_users)
urls.py
urlpatterns = patterns('',
url(r'get_data/','apps.api.views.get_data', name = 'grabhalo_get_data'),
)
jQuery
$(document).ready(function(){
$('#submit').click(function() {
var selected_users = $('input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
alert(selected_users); // works fine
$.post("get_data/",{users:selected_users}); // not able to post
});
})
复选框
{% for user in users %}
<input type="checkbox" class="check" value="{{user.id}}" />{{user.name}}<br>
{%endfor%}
<form id="form" method="POST" action="/get_data/">
{% csrf_token %}
<input type="text" class="span8 search-query" placeholder="Type here..." name="chat">
<input type="submit" value="Send" class = "btn btn-primary" id = "submit">
</form>
不同的建议是受欢迎的,如果有人可以重新定义.post功能。
Different Suggestions are welcomed , if anyone can redefine the .post function.
谢谢
推荐答案
你只需要结合@Aditya和@Yurly的答案:
You just have to combined @Aditya and @Yurly answers:
脚本
function get_csrf_token(){
return $("input[name='csrfmiddlewaretoken']").val();
}
$(document).ready(function(){
$('#submit').click(function() {
var datas = new Array();
var i = 0;
var csrf_token = get_csrf_token();
$("input[type=checkbox]:checked").each(function() {
datas[i] = $(this).val();
i++;
});
#make sure the url is correct
$.post("get_data/", {'users[]': datas, 'csrfmiddlewaretoken': csrf_token}, function(data){
alert(data);
});
});
})
views.py
if request.method == 'POST':
selected_users = request.POST.getlist('users[]')
return HttpResponse(selected_users)
这篇关于jQuery POST不返回变量用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!