我在获取POST请求以捕获所选复选框时遇到问题。有人建议我使用Ajax,所以我做了以下几点:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var SelectedItems = [];
$('.checkbox').click(function () {
var SelectedItems = $(this).val();
var index = SelectedItems.indexOf(SelectedItems);
var url = window.location.href.split('?')[0];
if (index == -1)
{
SelectedItems.push(SelectedItems);
} else {
SelectedItems.splice(index, 1);
}
});
$('#submit-button').click(function (event) {
event.preventDefault();
$.ajax({
url: "{% url 'requestaccess' %}",
data: JSON.stringify({ report_id: SelectedItems }),
dataType: 'json',
type: 'POST',
success: function (data) {
},
});
});
});
</script>
当我按下按钮时,我的chrome开发人员网络选项卡仅显示jquery.min是发起人。但是,当我在请求访问视图上打印我的request.POST调用作为get或getlist时,它显示空列表或NONE,我的Web应用程序在按下按钮时没有从/ account / profile切换到/ account / requestaccess:
[15/Nov/2017 15:04:02] "POST /account/requestaccess/ HTTP/1.1" 200 1031
None
[]
[15/Nov/2017 15:04:43] "POST /account/requestaccess/ HTTP/1.1" 200 1031
我对requestaccess的看法如下:
@csrf_exempt
def requestaccess(request):
import simplejson as json
owner = User.objects.get (formattedusername=request.user.formattedusername)
reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')
reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0)
checkedlist = request.POST.getlist('report_id')
checked = request.POST.get('report_id')
# checkboxvalue = request.POST['request_reports']
if request.method == 'POST':
print (checked)
print (checkedlist)
args = {'retreivecheckbox': checkedlist}
return render(request,'accounts/requestaccess.html')
为什么没有使用report_id的复选框值将report_id传递给requestaccess?如果我将POST更改为get,我可以看到当前视图中传递的值,并且我的url更改为/accounts/requestaccess.html。