Django项目:在AJAX中,parserror SyntaxError:JSON输入意外结束



我正在构建一个Django项目
点击按钮后,表单将被提交,并根据表单中的信息执行一些任务。然而,在我的情况下,任务可以正确完成,但总是会弹出错误提示:"parserror 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('')

正如错误所说,您需要从Django视图返回有效的JSON:

  • 空字符串不是有效的JSON,因此请确保您的响应以有效的JSON为主体
  • 此外(尽管在这种情况下可能不是关键的(,您应该将Content-Type标头设置为application/json,而不是text/html,这是HttpResponse的默认值。您可以使用Django的JsonResponse,也可以将正确的HTTP头添加到HttpResponse对象中

最新更新