本文旨在帮助开发者解决在使用 JavaScript 的 Ajax 发送请求到 Django 后端时遇到的请求失败问题。通过分析常见原因,并提供可行的解决方案和代码示例,帮助你成功实现前后端的数据交互。重点关注表单提交与 Ajax 请求的冲突,以及 Django 视图函数中跨域请求的处理。
在使用 JavaScript 通过 Ajax 向 Django 后端发送数据时,可能会遇到请求无法成功到达 success 回调函数的情况。这通常是由于多种原因造成的,包括表单提交行为的干扰、跨域请求问题、Django 视图函数中的错误处理,以及其他一些潜在的配置问题。下面将针对这些常见问题进行详细分析,并提供相应的解决方案。
当按钮类型为 submit 且位于
使用 button 标签代替 submit 按钮: 将
Send
function send() {
$.ajax({
type: 'POST',
url: "http://app.localhost/feedback",
dataType: "json",
data: {
feedback: $('#feedback').val(),
email: $('#email').val(),
},
success: function(json) {
$('Backdrop').hide();
console.log("requested access complete");
},
error: function(xhr, status, error) {
console.error("Error:", status, error);
}
});
}解释: 将按钮类型更改为 button 可以避免触发表单的默认提交行为,同时保留了 onclick 事件,确保 send() 函数能够被调用。
如果你的 Django 后端和 JavaScript 代码运行在不同的域名或端口上,就会遇到跨域请求问题。浏览器出于安全考虑,会阻止跨域请求。
解决方案:
使用 Django CORS Headers: 安装并配置 django-cors-headers 中间件,允许跨域请求。
pip install django-cors-headers
在 settings.py 文件中进行配置:
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:8000", # 允许的域名,根据实际情况修改
"http://127.0.0.1:8000",
]解释: django-cors-headers 中间件允许你配置允许跨域请求的域名。CORS_ALLOWED_ORIGINS 列表指定了允许跨域请求的域名。请根据你的实际情况修改该列表。
修改 Django 视图函数: 确保 Django 视图函数返回正确的响应头,允许跨域请求。
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def feedback(request):
if request.method == 'POST':
try:
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
fromField = body['email']
subject = 'New FeedBack from {}'.format(fromField)
body_text = body['feedback']
# sendEmail("[email protected]", subject, body,
# replyTo=['[email protected]', '[email protected]'])
print(f"Email: {fromField}, Feedback: {body_text}") # 模拟发送邮件
return JsonResponse({'status': 'success'}, status=200) # 返回 JSON 响应
except Exception as e:
print(f"Error processing request: {e}")
return JsonResponse({'status': 'error', 'message': str(e)}, status=400) # 返回错误信息
else:
return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)解释:
Django 默认启用了 CSRF 保护,防止跨站请求伪造攻击。当使用 Ajax 发送 POST 请求时,需要包含 CSRF token。
解决方案:
获取 CSRF token: 在 HTML 页面中获取 CSRF token。

在 Ajax 请求中包含 CSRF token: 将 CSRF token 添加到 Ajax 请求的头部。
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
$.ajax({
type: 'POST',
url: "http://app.localhost/feedback",
dataType: "json",
data: {
feedback: $('#feedback').val(),
email: $('#email').val(),
},
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function(json) {
$('Backdrop').hide();
console.log("requested access complete");
},
error: function(xhr, status, error) {
console.error("Error:", status, error);
}
});解释:
使用 @csrf_exempt 装饰器: 在 Django 视图函数中使用 @csrf_exempt 装饰器,禁用 CSRF 保护(不推荐,除非你确定不需要 CSRF 保护)。
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def feedback(request):
...警告: 禁用 CSRF 保护会使你的应用容易受到 CSRF 攻击,请谨慎使用。
解决 JavaScript Ajax 请求 Django 后端失败的问题需要综合考虑多个因素,包括表单提交行为的干扰、跨域请求问题、CSRF 保护以及其他潜在问题。通过仔细分析这些问题,并采取相应的解决方案,可以成功实现前后端的数据交互。在调试过程中,可以使用浏览器的开发者工具来查看网络请求和响应,以及 JavaScript 控制台的输出,以便更好地定位问题。