Ajax 代码无法向服务器发送请求,但是当我向同一 url 发出常规 http 请求时,它可以工作。我已经尝试将 url 字段替换为“http://”url,仍然无法正常工作。有人有想法吗?
Environment:
django 1.5.4;
python 2.7.4;
jquery 2.0.3;
test.html
<html>
<head>
<title></title>
<script type='text/javascript' src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
type : "POST",
url : "{% url 'getlist' %}",
data : {
msg : 'abcd'
},
}).done(function(data){
alert(data.message);
});
});
});
</script>
</head>
<body>
<input id="button" type="button" value="Get message from server!">
{% if resource_list %}
<ul>
{% for resource in resource_list %}
<li><a href="{{ resource.url }}">{{ resource.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No Resources</p>
{% endif %}
</body>
view.py
def getList(request):
print "Reach getLists"
if request.is_ajax():
try:
msg = request.POST['msg']
except:
return HttpResponse(simplejson.dumps({'message':'Error From Server'}))
return HttpResponse(simplejson.dumps({'message':msg}))
else:
return HttpResponse(simplejson.dumps({'message':'Not an ajax request'}))
urls.py
url(r'^test$', views.test),
url(r'^getlist/$', views.getList, name='getlist'),
====================================更新========== =========================== 错误信息
Forbidden (403)
CSRF 验证失败。请求中止。 帮助 给出的失败原因: CSRF token 丢失或不正确。
============================== 已解决 ================ ==================
解决方法:在JavaScript文件的data字段中添加“csrfmiddlewaretoken:'{{ csrf_token }}',”后就可以了。原因是django开启了CSRF保护。
==============================谢谢================ ====================
感谢@dkp2442 和@Christian Ternus 的帮助,尤其是@dkp2442。
最佳答案
我创建了一个 gist但以某种方式保密(我可以编辑吗??哈哈)。无论如何,您需要在帖子中包含 csrftoken。这是我的答案:
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]);
// 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;
}
您可以为您的任何帖子使用该 getCookie 函数,只需像这样包含它:
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
type : "POST",
url : "{% url 'getlist' %}",
data : {
msg : 'abcd',
csrfmiddlewaretoken: getCookie('csrftoken')
}
}).done(function(data){
alert(data.message);
});
});
});
关于javascript - jquery 函数无法向 django 服务器发送 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255923/