I practice in Django + Ajax. I use Ajax with jQuery. There is a form, I fill in the field, I press the button - the condition is checked. Problem: It produces the same result regardless of the number of characters. Error in syntax or ajax does not work for me at all?

html:

<script type="text/javascript"> $(function() { $("#done").click(function() { $.get("/create_test/", function(data) { alert(data); }); }); }); </script> </head> <body> <form action="" method="POST">{% csrf_token %} <input type="text" id="create"></input> <br><br><br> <input type="button" id="done" value="check"> </form> </body> 

view:

 def create(request): return render_to_response('create.html', {}, context_instance=RequestContext(request)) def create_test(request): if request.is_ajax(): text = request.POST.get('create', '') if len(text) <= 20: message = "AJAX: подходит!" return HttpResponse(message) else: message = "AJAX: не подходит!" return HttpResponse(message) else: message = "это не AJAX =(" return HttpResponse(message) 

Displays constantly "AJAX: suitable!" Received len (text) equal to 0. I understand that the request itself is not executed, i.e. data from the string is not transmitted and, accordingly, the length of the string is zero. So an error in the script, tell me what to add?

  • Received len (text) equal to 0. I understand that the request itself is not executed, i.e. data from the string is not transmitted and, accordingly, the length of the string is zero. So an error in the script, tell me what to add? - FlatOMG

1 answer 1

Try sending an ajax request like this:

 $("#done").click(function() { Data = $.("create").value; $.ajax({ url: "/create_test/", method: 'POST', data: { 'text': Data }, dataType: 'json', success: function(data) { alert(data); }, error: function(data){ alert('Записать данные не удалось'); }, }); }); 

Then you can receive a request in the form of json on the server like this:

 from json import loads text = loads(request.POST['text']) 

Or you can get the request as follows:

 text = request.POST['text'] 

Watching what data structure at you will be transferred as a result.