標籤:function span nbsp code rtc 執行個體 3.2 測試結果 head
需求:
(django)使用XMLHttpRequest和jQuery實現Ajax加法運算
url.py:
from django.conf.urls import urlfrom hello import viewsurlpatterns = [ url(r‘add/‘, views.add, name=‘add‘), url(r‘add_number/‘, views.add_number, name=‘add_number‘),]
add.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body><h1>XMLHttpRequest-Ajax請求</h1><input type="button" onclick="XmlRequest();" value="發送請求"><h1>jQuery-Ajax請求</h1><input type="button" onclick="JqRequest();" value="發送請求"><script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script><script type="text/javascript"> function XmlRequest() { var xhr = new XMLHttpRequest(); // 定義回呼函數 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { //已經接收到全部響應資料,執行以下操作 var data = xhr.responseText; console.log(data); } }; // 指定串連方式和地址--檔案方式 xhr.open(‘POST‘, {% url ‘add_number‘ %}, true); // 佈建要求頭 xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded;charset=UTF-8‘); // 發送請求 xhr.send(‘n1=2;n2=4;‘); } function JqRequest() { $.post({ url: {% url ‘add_number‘ %}, data: {"n1": 222, "n2": 444}, dataType: ‘text‘, success: function (data, statusText, xmlHttpRequest) { console.log(data); } }); }</script></body></html>
views.py
from django.http import HttpResponsefrom django.shortcuts import renderfrom django.views.decorators.csrf import csrf_exemptdef add(request): return render(request, ‘add.html‘)@csrf_exemptdef add_number(request): method = request.method n1 = request.POST.get(‘n1‘) n2 = request.POST.get(‘n2‘) result = int(n1) + int(n2) content = ‘{"method":%s,"result":%s}‘ % (method, result) return HttpResponse(content)
測試結果如:
Ajax-05 使用XMLHttpRequest和jQuery實現Ajax執行個體