Django based ajax

Take control of your own destiny
Destiny is in your hands

This article is mainly used to record some usages and points of attention of django+ajax. One of the biggest uses of Ajanx in Django is to request the server content to change the value of some elements in the page without refreshing the entire page. If you use an http request, you must reload the page, and ajax can only change a portion of the content.

django+ajax basic use

Template page

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form>
<input type="text" id="tn">
</form>
<span id='result'></span>
<script>
$(document).ready(function(){
$("#formquery").click(function(){
var toolsname = $("#tn").val();
$.get("/query/",{'toolsname':toolsname}, function(ret){
$('#result').html(ret) #Show on the page. You can use $.ajax instead of $.get
})
});
});
</script>

Description of the parameters of the above code:

  • $.get means that ajax sends a request using GET, or it can be changed to $.ajax, or $.post for post request.
  • id=”tn” corresponds to the parameter name $(“#tn”) obtained in js
  • id=”formquery” corresponds to the function name of the js corresponding to the button event
  • id=’result’ corresponds to the location where the result is returned $(‘#result’)

Note: It should be noted here that the type of the button cannot write submit, because the submit request directly uses the get request /query/, and does not execute the ajax request.

view.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.http import HttpResponse
def query(request):
r=request.GET.get("toolsname")
name_dict="123"
return HttpResponse(json.dumps(name_dict), content_type='application/json')
Or you can use JsonResponse:
from django.http import JsonResponse
def query(request):
r=request.GET.get("toolsname")
name_dict="123"
return JsonResponse(name_dict)

Description: In the view layer, view.py, it is the same as the normal way to accept http requests. The requests.is_ajax() method can be used in views.py to determine if it is an ajax request.

Some advanced usages of ajax

Wait until I finish the experiment and record again…

ajax gets the return value and executes js

1
2
3
4
5
6
7
8
9
10
11
<textarea name="content" id="content" class="form-control" rows="20"></textarea>
<script>
$(document).ready(function(){
$("#sub_encode").click(function(){
var content = $ ("# content") .val ();
$.get("/add/",{'content':content}, function(ret){
document.getElementById('content').value = ret
})
});
</script>

Description: After getting the return value, fill the return value into the textarea text box.

ajax+post CSRF Certification

Before the ajax code, add the following js.

1
2
3
4
5
<script>
$ .ajaxSetup ({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
</script>

ajax+ button loading transition

Sometimes some functions in the webpage take a long time to wait. It is better to use ajax at this time, because it does not require the entire web page refresh, and the user experience is better. The meaning of the button loading transition is that when you click the button, the button font content becomes “Loading”, and then resumes after ajax returns the content, which will make the experience better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- Integrate the code for the button transition into ajax -->
<script>
$(document).ready(function(){
$("#sub_encode").click(function(){
var content = $ ("# content") .val ();
Var btn = $("#sub_encode"); //Get the button object
Btn.button('loading');// button is displayed as a transition state
$.post("{% url 'run_ajax' %}",{'content':content,"type":"encode"}, function(ret){
document.getElementById('content').value = ret
Btn.button('reset');//The button returns to normal
})
});
</script>
<!-- bottom loading js -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

ajax+list dictionary return

How does ajax return to a page when it is a json-formatted list or dictionary? As follows, if the data returned by the backend is json:[{“a”:”1”,”b”:”2”},{“c”:3,”d”:”4”}]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tn" placeholder="Please enter a search keyword">
<button type="button" id="formquery" data-loading-text="Effort loading..." autocomplete="off" onclick="loag()">Search </button>
<!-- Search result list -->
<p id="list_result" style="word-wrap:break-word;word-break:break-all;"></p>
<!-- ajax request -->
<script>
$(document).ready(function(){
$('#formquery').click(function(){
var q = $ ("# tn") .val ();
Var btn = $("#formquery"); //Get the button object
Btn.button('loading');// button is displayed as a transition state
$.getJSON('/search/',{"q":q},function(ret){
document.getElementById('list_result').innerText = ""; // Reset the contents of <p>
$.each(ret, function(i,item){ // traverse list
$.each(item, function(key,value){ // traverse dictionary
$('#list_result').append(key":"+value)
});
});
btn.button('reset');
})
})
});
</script>
<!-- bottom loading js -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

ajax with page auto refresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<input type="hidden" id="formquery" onclick="loag()"> # button (hidden)
<div id="task_schedule_result"></div> # Where to display content
# When clicking the button thing, send ajax request js
<script>
$(document).ready(function(){
$('#formquery').click(function(){
$.getJSON("{% url 'task_schedule' %}",function(ret){
document.getElementById('task_schedule_result').innerHTML = ret;
})
})
});
</script>
#Auto click button js
<script type="text/javascript">
function myrefresh(){
document.getElementById('formquery').click();
}
setInterval("myrefresh()","10000"); #Execute a click button every 10 seconds
</script>

Description: The above html code uses the ajax request every 10s to get the backend data code.

Reference

http://code.ziqiangxuetang.com/django/django-ajax.html

本文标题:Django based ajax

文章作者:nmask

发布时间:2017年09月14日 - 19:09

最后更新:2019年07月11日 - 17:07

原始链接:https://thief.one/2017/09/14/3/en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: