1.Ajax
1.原生Ajax,XMLHttpRequest
2.jQuery Ajax,內部基於’原生Ajax’
2.僞Ajax,非XMLHttpRequest
- 1.Ajax
- JQuery Ajax
# views.py
def index(request):
return render(request,'index.html')
def add1(request):
print(request.POST)
a1 = int(request.POST.get('il1'))
a2 = int(request.POST.get('il2'))
return HttpResponse(a1 + a2)
# index.html
<body>
<input type="text" id="il1" />
+
<input type="text" id="il2" />
=
<input type="text" id="il3" />
<input type="button" value="JQuery Ajax" id="btn1" onclick="add1()">
<input type="button" value="原生 Ajax" id="btn2" onclick="add2()">
</body>
<script src="/static/jquery-3.2.1.js"></script>
<script>
// jQuery Ajax,內部基於'原生Ajax'
function add1() {
$.ajax({
url: '/add1/',
type: 'POST',
data:{'il1':$('#il1').val(),'il2':$('#il2').val()},
success:function (arg) {
$('#il3').val(arg)
}
})
}
</script>
- 原生Ajax,XMLHttpRequest
# views.py
def add2(request):
if request.method == 'GET':
a1 = int(request.GET.get('il1'))
a2 = int(request.GET.get('il2'))
print('add2....')
return HttpResponse(a1 + a2)
else:
a1 = int(request.POST.get('il1'))
a2 = int(request.POST.get('il2'))
return HttpResponse(a1 + a2)
# index.html
...
<script src="/static/jquery-3.2.1.js"></script>
<script>
# 原生Ajax,GET請求
function add2() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
};
xhr.open('GET','/add2/?il1=12&il2=19');
xhr.send();
}
# 原生Ajax,POST請求
function add2() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
};
xhr.open('POST','/add2/');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');// 加請求頭
xhr.send('il1=12&il2=19');
}
</script>