help please send ajax-request.
html:
<p><a id="test">Hello</a></p>
js:
$(function() {
$("#test").click(function() {
$.ajax({
url: "/xhr_test/",
type: 'POST',
dataType:"html",
data: {
"phone": 1,
"skype": 2,
"other": 3,
},
error: function() {
alert('Ошибка получения запроса');
},
success: function(data) {
alert('ajax worked' + data);
}
});
});
});
urls.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)
I try to check the data before sending mail using js:
the problem is that after submitting the form I get the message "error mes". at the same time to the browser console output: POST http: // localhost: 8000 / xhr_test / 403 (FORBIDDEN)
please help fix the code
You need to send CSRF
token as well in your request.
From your view pass csrf token to template that will generate your web page, then pass that csrf
token back with your ajax
call,so that django recognises you as valid connection.
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 template
{% csrf_token %}
<p><a id="test">Hello</a></p>
views.py
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")
you need to include the csrfmiddlewaretoken
in your ajax call.
$(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);
}
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.