1. JS实现Ajax
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button type="submit" id="js_ajax_test">Ajax测试</button> <script> var js_ajax_test = document.getElementById("js_ajax_test"); js_ajax_test = function () { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("POST", "/js_ajax_test/", true); xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlHttp.send("username=yang&password=123"); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4 && xmlHttp.status ===200){ alert(xmlHttp.responseText) } } } </script> </body> </html>
2. jQuery实现的Ajax
最基本的jQuery发送Ajax请求示例:
<!doctype html> <html lang=""> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <title>ajax test</title> </head> <body> <button id="ajaxTest">AJAX测试</button> <script> $("#ajaxTest").click(function () { $.ajax({ url: "/ajaxTest/", type: "POST", data: {username: "yang", password:123}, success: function (data) { alert(data) } }) }) </script> </body> </html>
views.py
def ajax_test(request): return render(request, "ajax_test.html") def ajaxTest(request): username = request.POST.get("username") password = request.POST.get("password") return HttpResponse("用户名:{} 密码:{}".format(username, password))
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^ajax_test/', views.ajax_test), url(r'^ajaxTest/', views.ajaxTest) ]
3. Ajax中使用JSON
data参数中的键值对,如果值不为字符串,需要将其转换成字符串类型。
如果没有转换为字符串,那么views中的代码就接收不到password的值。
<script> $("#ajaxTest").click(function () { $.ajax({ url: "/ajaxTest/", type: "POST", data: {username: "yang", password:JSON.stringify([1, 2, 3])}, success: function (data) { alert(data) } }) }) </script>