Answer the question
In order to leave comments, you need to log in
Why is there a redirect to localhost:8000/ after sending a POST request via AJAX?
I use jQuery AJAX and Django.
When you click the "Add" button, a POST request is sent (csrf token is created using the csrf.js file, as in the documentation ), the source address of the local server is localhost:8000, after sending the request it changes to - localhost:8000/?. Why is this happening? A snippet of the index.html
file :
<form>
<input type = "text" id = "task_text"><input type = "submit" value = "Добавить" id = "add">
</form>
$('#add').click(function()
{
text = $('#task_text').val();
$.ajax(
{
url: '/test/',
type: 'POST',
data: {task_text: text},
success: function(text){
console.log(text)
},
});
});
def test(request):
if request.is_ajax():
r = request.POST['task_text']
Task.objects.create(text = r)
return redirect('/')
else:
message = "bad"
return HttpResponse(message)
<form>
and <input type = "submit">
using only <input type = "button">
and index.js file?Answer the question
In order to leave comments, you need to log in
the initial address of the local server is localhost:8000, after sending the request it changes to - localhost:8000/?. Why is this happening?Apparently because of this line:
Is it possible to use AJAX without a formYou can hang a click handler on the button and send an ajax request inside. You actually do this, so the form can simply be removed from the markup.
$('#add').click(function()
{
text = $('#task_text').val();
$.ajax(
{
url: '/test/',
type: 'POST',
data: {task_text: text},
success: function(text){
console.log(text)
},
return false;
});
});
still at the moment pay attention djbook.ru/rel1.8/ref/settings.html#append-slash
You have the same view in the view:
Write
success: function(text){
alert(response['msg'])
},
msg_value = 'Your text is add!'
response_data['msg'] = unicode(msg_value)
return JsonResponse(response_data)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question