一、Ajax
在之前学习jQuery的时候,我们选择使用1.x版本,而没有选择使用2.x、3.x版本。
主要是因为1.x版本兼容以前比较老的浏览器,例如IE6 IE7等。
例如要使用Ajax,低版本的浏览器可能不支持xmlHttpRequest对象,而只支持另外一种替代对象叫ActiveXObject。
在jQuery 1.x中,jquery.ajax会对这两种对象进行上层封装,也就是说两种都支持。
但在2.x和3.x中,jquery就放弃了低版本的浏览器,而只支持XHR对象。
1.使用原生Ajax(GET请求)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax</title> </head> <body> <input type="text"/> <input type="button" value="Ajax" onclick="send_ajax();"/> <script> // onclick事件,发送原生ajax请求 function send_ajax() { // 创建一个xhr对象 var xhr = new XMLHttpRequest(); // 建立异步连接,第三个参数true表示异步 xhr.open('GET', '/ajaxproc/', true); // 指定回调函数,每当readystate的值改变时,function就会被执行,当readystate为4时表示收到返回的数据 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { // 打印收到的数据 console.log(xhr.responseText); // 打印收到的状态码,这个码是由视图函数HttpResponse(status=200)返回 console.log(xhr.status); // 打印状态码对应的文本,HttpResponse(reason='文本')返回 console.log(xhr.statusText); } }; // 发送数据 xhr.send("username=root;password=123456"); } </script> </body> </html>
2.使用原生Ajax(POST请求)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax</title> </head> <body> <input type="text"/> <input type="button" value="Ajax" onclick="Ajax1();"/> <script> // onclick事件,发送原生ajax请求 function Ajax1() { // 创建一个xhr对象 var xhr = new XMLHttpRequest(); // 建立异步连接,第三个参数true表示异步 xhr.open('POST', '/ajaxproc/', true); // 指定回调函数,每当readystate的值改变时,function就会被执行,当readystate为4时表示收到返回的数据 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { // 打印收到的数据 console.log(xhr.responseText); // 打印收到的状态码,这个码是由视图函数HttpResponse(status=200)返回 console.log(xhr.status); // 打印状态码对应的文本,HttpResponse(reason='文本')返回 console.log(xhr.statusText); } }; // 要发post请求,必须设置请求头 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); // 主要要设置csrf,这里省略,参考CSRF章节 // 发送数据 xhr.send("username=root;password=1234;"); } </script> </body> </html>
3.对应视图函数
def ajax(request): return render(request, 'ajax.html') def ajaxproc(request): import json def check_data(u, p): if u == 'leo' and p == '123456': return True else: return False if request.method == 'GET': if check_data(request.GET.get('username'), request.GET.get('password')): ret = {'code': 2000, 'data': "正确"} else: ret = {'code': 4000, 'data': "错误"} return HttpResponse(json.dumps(ret), status=200, reason="OK") if request.method == 'POST': if check_data(request.POST.get('username'), request.POST.get('password')): ret = {'code': 2000, 'data': "正确"} else: ret = {'code': 4000, 'data': "错误"} return HttpResponse(json.dumps(ret), status=200, reason="OK")