Netty 框架學習 —— EventLoop 和執行緒模型
一、Ajax介紹
AJAX(Asynchronous Javascript And XML)翻譯成中文就是 “ 非同步的Javascript和XML ”。
- Ajax不是新的程式語言,而是一種使用現有標準的新方法。
- Ajax最大的優點是在不重新載入整個頁面的情況下,可以與伺服器交換資料並更新部分網頁內容。
- Ajax不需要任何瀏覽器外掛,但需要使用者允許JavaScript在瀏覽器上執行。
Ajax常見應用情景:
- 搜尋引擎根據使用者輸入的關鍵字,自動提示檢索關鍵字。
- 註冊時候的使用者名稱的查重。
優點:
- Ajax使用JavaScript技術向伺服器傳送非同步請求
- Ajax請求無須重新整理整個頁面
- 應為伺服器響應內容不再是整個頁面,而是頁面中的部分內容,所以Ajax效能高
兩大特性
- 非同步請求:客戶端傳送一個請求後,無需等待伺服器響應結束就可以發第二個請求
- 區域性重新整理:(這一特點給使用者感受是在不知不覺中完成請求和響應過程)
例子:通過Ajax請求判斷使用者名稱密碼是否輸入錯誤,並且不重新整理網頁,只在對應密碼後面提示!,驗證正確通過js跳轉頁面。
login.html 頁面
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>歡迎登入頁面</h1> <form action=""> {% csrf_token %} <label for="username">使用者名稱:</label><input type="text" id="username"> <label for="password">密碼:</label><input type="password" id="password"> <input type="button" value="確認" id="d1"> </form> <script src="{% static 'js/jQuery.js' %}"></script> <script> let state = true; $('#d1').click(function () { // 觸發點選事件 $.ajax({ url: "{% url 'login' %}", // 請求地址 type: 'post', // 請求方法 data: { // 請求資料 'uname': $('#username').val(), 'pwd': $('#password').val(), 'csrfmiddlewaretoken': '{{ csrf_token }}', // post請求提交csrf_token資料 }, success: function (ret) { // 獲取返回引數並且自動序列化ret,並且執行function方法 if (ret['state'] === 3) { // 使用者密碼驗證成功,進行跳轉到伺服器返回的指定地址 location.href = ret['url']; } else if (ret['state'] === 0) { // 驗證失敗,建立標籤並新增內容,插入到form表單之後,只插入一次。 if (state) { const p = document.createElement("span"); p.innerText = ret['error']; $('form').append(p); state = false; } } }, }) }) </script> </body> </html>
views.py 檔案
from django.shortcuts import render, reverse from django.http import JsonResponse from django.views import View class Login_view(View): def get(self, request): return render(request, 'login.html') def post(self, request): name = request.POST.get('uname') pwd = request.POST.get('pwd') if name == 'xiaoyang' and pwd == '123': data = {'state': 3, 'url': reverse('index')} return JsonResponse(data) # 以json格式傳送data字典 else: data = {'state': 0, 'error': '使用者名稱或密碼錯誤'} return JsonResponse(data) def index(request): return render(request, 'index.html')
二、Ajax引數
請求引數
date:
當前Ajax請求要攜帶的資料,是一個json的object物件,Ajax方法就會預設把它編碼成某種格式
function f() {
$.ajax({
url: '/index/',
type: 'get',
data: { // 此時data是一個json形式的物件
'k1': 'v1',
'k2': 'v2',
},
})
}
processData:
聲明當前data資料是否進行轉碼或預處理,預設為true,即預處理;
如果是false,那麼對data:{'k1':'v1', 'k2':'v2'} 會呼叫json物件的toString( ) 方法,也就是{'k1':'v1', 'k2':'v2'}.toString( ),最後得到一個[object, Object]形式的結果
function f() {
$.ajax({
url: '/index/',
type: 'get',
processData: false,
data: { // 此時data是[object, Object]
'k1': 'v1',
'k2': 'v2',
},
})
}
contentType:
預設值:"application/x-www-form-urlencoded"
是傳送資訊到伺服器時內容編碼型別,用來指明當前請求的資料編碼格式;
比如:contentType:"application/json",向伺服器傳送一個json字串。
function f() {
$.ajax({
url: '/index/',
type: 'post',
processData: false,
data: {
'k1': 'v1',
'k2': 'v2',
},
contentType: 'application/json',
})
}
// 一旦設定,data必須使json字串,不能是json物件
// wiews.py 檔案:json.loads(request.body.decode('utf8'))
響應引數
dataType:
把伺服器返回的資料型別根據這個值解析後,傳遞給回掉函式。
預設不需要指定這個屬性,Ajax會根據伺服器返回的 content Type 來進行轉換。
例如:
我們伺服器響應的 content Type為json格式,這時Ajax方法就會對響應的內容進行一個json格式的轉換,如果轉換成功,我們在 success 的回撥函式裡就會得到一個json格式的物件:轉換失敗就會觸發error這個回撥函式。如果明確的指定目標型別,就可以使用 data Type。
dataType的可用值:html、xml、json、text、script
function f() {
$.ajax({
url: '/index/',
type: 'get',
dataType: 'json',
data: {'obj': 'getjson'},
success: function (ret) {
console.log(ret); // 此時會自動將返回的字串轉換成json物件。
},
error: function () {
alert('轉換失敗!');
}
})
}
三、json時間格式轉換
import json
from datetime import datetime
from datetime import date
# 對含有日期格式資料的json資料進行轉換
class JsonCustomEncoder(json.JSONEncoder):
def default(self, field):
if isinstance(field,datetime):
return field.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(field,date):
return field.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self,field)
d1 = datetime.now()
dd = json.dumps(d1,cls=JsonCustomEncoder) # 轉換
print(dd)