
本文旨在帮助开发者解决在使用 JavaScript 的 Ajax 发送请求到 Django 后端时遇到的请求失败问题。通过分析常见原因,并提供可行的解决方案和代码示例,帮助你成功实现前后端的数据交互。重点关注表单提交与 Ajax 请求的冲突,以及 Django 视图函数中跨域请求的处理。
在使用 JavaScript 通过 Ajax 向 Django 后端发送数据时,可能会遇到请求无法成功到达 success 回调函数的情况。这通常是由于多种原因造成的,包括表单提交行为的干扰、跨域请求问题、Django 视图函数中的错误处理,以及其他一些潜在的配置问题。下面将针对这些常见问题进行详细分析,并提供相应的解决方案。
当按钮类型为 submit 且位于 <form> 标签内时,点击按钮会触发表单的默认提交行为。这种默认行为会导致页面刷新或跳转,从而中断 Ajax 请求的发送和接收过程。
解决方案:
立即学习“Java免费学习笔记(深入)”;
阻止表单的默认提交行为: 将按钮从 <form> 标签中移除,或者使用 JavaScript 阻止表单的默认提交行为。
<form id="myForm">
<input type="text" id="feedback" name="feedback">
<input type="email" id="email" name="email">
<button type="submit" id="post-form" class="btn btn-primary">Send</button>
</form>$("#myForm").submit(function(event) {
event.preventDefault(); // 阻止表单默认提交
$.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);
}
});
});解释: event.preventDefault() 方法用于阻止表单的默认提交行为,确保 Ajax 请求能够正常发送。同时,添加了 error 回调函数,以便在请求失败时能够捕获错误信息。
使用 button 标签代替 submit 按钮: 将 <button type="submit"> 更改为 <button type="button">,并保留 onclick 事件。这样可以避免触发表单的默认提交行为。
<button type="button" id="post-form" class="btn btn-primary" onclick="send()">Send</button>
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 代码运行在不同的域名或端口上,就会遇到跨域请求问题。浏览器出于安全考虑,会阻止跨域请求。
解决方案:
立即学习“Java免费学习笔记(深入)”;
使用 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("<a class="__cf_email__" data-cfemail="1b7e635b7e63357874" href="/cdn-cgi/l/email-protection">[email protected]</a>", subject, body,
# replyTo=['<a class="__cf_email__" data-cfemail="55302d15302d7b363a" href="/cdn-cgi/l/email-protection">[email protected]</a>', '<a class="__cf_email__" data-cfemail="d6b3aef8b3ae96b1bbb7bfbaf8b5b9bb" href="/cdn-cgi/l/email-protection">[email protected]</a>'])
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。
解决方案:
立即学习“Java免费学习笔记(深入)”;
获取 CSRF token: 在 HTML 页面中获取 CSRF token。
<input type="hidden" name="csrfmiddlewaretoken" value="{{ 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 控制台的输出,以便更好地定位问题。
以上就是解决 JavaScript Ajax 请求 Django 后端失败的问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号