【发布时间】:2015-12-30 05:05:29
【问题描述】:
我无法在移动平台上测试我使用 django 开发的网站。我设置了我的服务器,以便它使用 javascript 在滚动时从 django 视图中使用 ajax 连续加载帖子。
当我从命令行运行我的服务器并在桌面浏览器上对其进行测试时,该服务运行良好,并且我的帖子持续加载,没有任何 403 禁止错误。但是,当我尝试在手机上对其进行测试时,我可以在服务器的命令输出中看到一个请求已获得 403 禁止响应。
我不确定是什么原因造成的,因为我已经考虑到在进行 ajax 调用之前需要加载 csrf 令牌。
这是我用来加载我的 csrf 令牌的代码。
$(document).ready(function () {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
这是通过ajax连续调用的视图代码。
# Get a post item
def get_posts (request):
# Catch any errors
try:
# Request for home post
if request.POST['type'] == 'home':
# Post index to fetch
index = int(request.POST['index'])
# Fetch the post of the specified index
posts = HomePost.objects.all()
# Specified index does not exist
if index >= len(posts):
# 400 client error response
return HttpResponse(status='400')
# Template the post into an html string, cut off './' from image url
post_html = render_to_string('home_post.html', {'image': str(posts[index].image)[2:], 'body': posts[index].body});
# Return the templated post html
return HttpResponse(post_html)
# Error while parsing
except:
# 500 internal server error response
return HttpResponse(status='500')
编辑:
我进一步测试了哪些特定浏览器会导致同样的问题,我得出的结论是 chrome 桌面是唯一没有这个问题的浏览器。
【问题讨论】:
标签: jquery ajax django http-status-code-403