我正在构建Django项目。
单击按钮后,将提交表单,并根据表单中的信息执行一些任务。但是,就我而言,可以正常执行任务,同时总是弹出错误消息:“ parsererror SyntaxError:JSON输入意外结束”。
这是我的AJAX函数:
$(document).on('submit', '#productForm', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
dataType: 'json',
url: 'product/',
data: {
region: $("#Region-choice").val(),
country: $("#Country-choice").val(),
product: $("#Product-choice").val(),
dvn: $("#dvn").val(),
reship: $("#reshipCheckbox").val(),
reshipId: $("#reshipTextfield").val(),
validator: $("#Validator").val()}
})
.done(function(){
alert("Product Created!");
})
.fail(function(req, textStatus, errorThrown) {
alert("Something went wrong!:" + textStatus + ' ' + errorThrown );
});
alert("Submitted!");
});
查看功能:
def viewCreateProduct(request):
"""The .delay() call here is to convert the function to be called asynchronously"""
if request.method == 'POST':
region = request.POST.get('region')
country = request.POST.get('country')
product = request.POST.get('product')
dvn = request.POST.get('dvn')
reship = request.POST.get('reship')
reshipId = request.POST.get('reshipId')
validator = request.POST.get('validator')
task = createProduct.delay(region, country, product, dvn, reship, reshipId, validator)
return HttpResponse('')
答案 0 :(得分:1)
如错误所述,您需要从Django视图返回有效的JSON:
application/json
而不是text/html
的{{1}}。您可以改用Django的HttpResponse
或将正确的HTTP标头添加到JsonResponse
对象。