问题
I am having issues getting my POST request to capture the selected check boxes. It's been suggested to me to use Ajax so I did with the following:
<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>
When I push the button my chrome developer Network tab only shows the jquery.min being the initiator. However, when I print my request.POST call as a get or getlist on the request access view it displays either an emptylist or NONE, my web application isn't switching from /account/profile to /account/requestaccess on the button press:
[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
My view for requestaccess is the following:
@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')
Any idea as to why report_id is not being passed to requestaccess with the checkbox values of report_id? If i change my POST to a get I can see the values being passed in the current view and my url changes to /accounts/requestaccess.html.
来源:https://stackoverflow.com/questions/47317352/ajax-call-not-being-passed-post-request-shows-as-none