非常简单的任务。有必要使用AJAX POST将表单中的数据与其他数据一起传输。问题是如何从表单中提取这些数据,因为它们代表整行。
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var form=$('#myform').serialize();
var data={};
data['form']=form;
data['csrfmiddlewaretoken']='{{ csrf_token }}';
data['other_data']='other_data';
$.ajax({
type: 'POST',
url: '/myajaxformview',
dataType: 'json',
data: data,
success: function (data, textStatus) {
$('#output2').html(JSON.stringify(data));
},
error: function(xhr, status, e) {
alert(status, e);
}
});
});
});
def myajaxformview(request):
if request.method == 'POST':
if request.is_ajax():
data = request.POST
print(data)
#<QueryDict: {'form': ['csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2'], 'csrfmiddlewaretoken': ['VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9'], 'other_data': ['other_data']}>
form=data.get('form')
#csrfmiddlewaretoken=VtBJ03YJZsEocJ5sxl9RqATdu38QBPgu4yPAC64JlpjOzILlF1fOQj54TotABHx9&field1=1&field2=2
print(form)
return HttpResponse(json.dumps(data))
return render(request, 'foo.html')
答案 0 :(得分:0)
考虑使用FormData
:
$(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var data = new FormData(event.target);
data.append('form', event.target);
data.append('csrfmiddlewaretoken', '{{ csrf_token }}');
data.append('other_data', 'other_data');
$.ajax({
type: 'POST',
url: '/myajaxformview',
dataType: 'json',
data: data,
processData: false,
contentType: false,
success: function (data, textStatus) {
$('#output2').html(JSON.stringify(data));
},
error: function(xhr, status, e) {
alert(status, e);
}
});
});
});