Javascript 如何简单地发送ajax请求?
帮助请发送ajax请求 html: URL.py:Javascript 如何简单地发送ajax请求?,javascript,jquery,python,django,Javascript,Jquery,Python,Django,帮助请发送ajax请求 html: URL.py: url(r'^xhr_test/$', 'views.xhr_test', name='xhr_test'), views.py: def xhr_test(request): if request.is_ajax(): message = "Hello AJAX!" else: message = "Hello" return HttpResponse(message) 我
url(r'^xhr_test/$', 'views.xhr_test', name='xhr_test'),
views.py:
def xhr_test(request):
if request.is_ajax():
message = "Hello AJAX!"
else:
message = "Hello"
return HttpResponse(message)
我尝试在使用js发送邮件之前检查数据:
问题是,在提交表单后,我收到消息“error mes”。同时向浏览器控制台输出:POST http://localhost:8000/xhr_test/403(禁止)
请帮助修复您需要在请求中发送
CSRF
令牌的代码
从您的视图中,将csrf令牌传递给将生成您的网页的模板,然后使用ajax
调用将该csrf
令牌传递回,以便django将您识别为有效连接
Javascript
$(function() {
$("#test").click(function() {
$.ajax({
url: "/xhr_test",
type: 'POST',
dataType:"json",
data: {
"phone": 1,
"skype": 2,
"other": 3,
"csrfmiddlewaretoken": '{{ csrf_token }}'
},
error: function() {
alert('Ошибка получения запроса');
},
success: function(data) {
alert('ajax worked' + data);
}
});
});
});
HTML模板
{% csrf_token %}
<p><a id="test">Hello</a></p>
您需要在ajax调用中包含
csrfmiddlewaretoken
$(function() {
$("#test").click(function() {
$.ajax({
url: "/xhr_test/",
type: 'POST',
dataType: "html",
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
phone: 1,
skype: 2,
other: 3,
},
error: function() {
alert('Ошибка получения запроса');
},
success: function(data) {
alert('ajax worked' + data);
}
});
});
});
非常感谢。但是在我发送的表单中:csrfmiddlewaretoken:$(“#myForm input[name=csrfmiddlewaretoken]”).val(),但我现在的问题不是表单。所以不清楚{{csrf_token}中包含了什么值,但我现在的问题不是形式…Hello我现在已经测试了它,没有形式,它可以工作,并将代码添加到答案中。
{% csrf_token %}
<p><a id="test">Hello</a></p>
def xhr_test(request):
if request.is_ajax():
phone = request.POST['phone']
data_to_send = {}
data_to_send.update({'data':phone})
return HttpResponse(simplejson.dumps(data_to_send),content_type="application/json")
$(function() {
$("#test").click(function() {
$.ajax({
url: "/xhr_test/",
type: 'POST',
dataType: "html",
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
phone: 1,
skype: 2,
other: 3,
},
error: function() {
alert('Ошибка получения запроса');
},
success: function(data) {
alert('ajax worked' + data);
}
});
});
});