day72 Ajax 第一天
第一个示例:(i1+i2 )
前端数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="i1">+ <input type="text" id="i2">= <input type="text" id="i3"> <input type="button" value="ajax请求" id="b1"> <script src="/static/jquery-3.3.1.js"></script> <script> $("#b1").on("click",function () { //点击id是b1的按钮要做的事 var i1 =$("#i1").val(); var i2 =$("#i2").val(); //往后端提前数据 $.ajax({ url:"/ajax_add/", type:"get", data:{"i1":i1,"i2":i2}, success:function (arg) { alert(arg); $("#i3").val(arg) } }) }) </script> </body> </html>
view视图
from django.shortcuts import render,HttpResponse # Create your views here. def index(request): return render(request,'index.html') def ajax_add(request): print("+++++++++++++++++++++++") print(request.GET) # print(request.GET.get("i1")) # print(request.GET.get("i2")) i1 =int(request.GET.get("i1")) i2 =int(request.GET.get("i2")) ret =i1+i2 return HttpResponse(ret)
第二个示例(post请求+get)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% csrf_token %} <input type="text" id="i1">+ <input type="text" id="i2">= <input type="text" id="i3"> <input type="button" value="get请求" id="b1"> <input type="button" value="post请求" id="b3"> <script src="/static/jquery-3.3.1.js"></script> <script> {###################下面为GET请求#################} $("#b1").on("click",function () { //点击id是b1的按钮要做的事 var i1 =$("#i1").val(); var i2 =$("#i2").val(); //往后端提前数据 $.ajax({ url:"/ajax_add/", type:"get", data:{"i1":i1,"i2":i2}, success:function (arg) { {#alert(arg);#} $("#i3").val(arg) } }) }) {###################下面为post请求带上csrftoken#################} $("#b3").on("click",function () { //点击id是b1的按钮要做的事 var i1 =$("#i1").val(); var i2 =$("#i2").val(); //找到页面上的csrftoken var csrfToken=$("[name='csrfmiddlewaretoken']").val(); //往后端提前数据 $.ajax({ url:"/ajax_add3/", type:"post", data:{"i1":i1,"i2":i2,"csrfmiddlewaretoken":csrfToken}, success:function (arg) { {#alert(arg);#} $("#i3").val(arg) } }) }) </script> </body> </html>
views视图
from django.shortcuts import render,HttpResponse # Create your views here. def index(request): return render(request,'index.html') def ajax_add(request): print("get请求+++++++++++++++++++++++") print(request.GET) # print(request.GET.get("i1")) # print(request.GET.get("i2")) i1 =int(request.GET.get("i1")) i2 =int(request.GET.get("i2")) ret =i1+i2 return HttpResponse(ret) def ajax_add3(request): print("post请求+++++++++++++++++++++++") print(request.POST) # print(request.GET.get("i1")) # print(request.GET.get("i2")) i1 =int(request.POST.get("i1")) i2 =int(request.POST.get("i2")) ret =i1+i2 return HttpResponse(ret)
路由配置
""" from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r"^ajax_add/",views.ajax_add), # get请求 url(r"^ajax_add3/",views.ajax_add3), #post请求 ]
三、部分序列化知识
===================================================================================================================================
一、什么是ajax ?
1.什么是json
json指的是javascript对象表示法(javascript object notation)
json是轻量级的文本数据交换格式.
json独立于语言
json 使用javascript 语法来描述数据对象,但json仍然独立于语言和平台。
pickle只有python能用.
一 、案例
一、HTML 语言文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <input type="text" id="i1">+ <input type="text" id ='i2'>= <input type="text" id ='i3'> <input type="button" value="ajax提交" id="b1"> <script src="/static/jquery-3.3.1.js"></script> <script> $('#b1').on('click',function(){ //点击id是b1的按钮要做的事 var i1 =$('#i1').val(); var i2 =$('#i2').val(); //往后端发数据 $.ajax({ url:'/ajax_add/', type:'get', data:{'i1':i1,'i2':i2}, success:function (args) { {#alert(args);#} // 把返回的结果填充到id是id的input框中 $('#i3').val(args) } }) }); </script> </body> </html>
二、URL文件
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_add/',views.ajax_add), url(r'^login/$',views.login), # url( r'^transfer/',views.transfer), url(r'^home/',views.home), url(r'^ajax_add/',views.ajax_add), url(r'^index/',views.index), url(r'^test/',views.test), ]
三、views文件
def ajax_add(request): print(request.GET) print(request.GET.get('i1')) print(request.GET.get('i2')) i1 =int(request.GET.get('i1')) i2 =int(request.GET.get('i2')) ret =i1 +i2 return HttpResponse(ret)
四、输出结果
五、访问网页
三、Ajax 发送post请求
<form action="/form_add/" method="post"> {% csrf_token %} <input type="text" name="user"> <input type="password" name="pwd"> <input type="submit"> </form> <script src="/static/jquery-3.3.1.js"></script> <script src="/static/setupajax.js"></script> <script> $("#b1").on("click", function () { // 点击 id是b1的按钮要做的事儿 var i1 = $("#i1").val(); var i2 = $("#i2").val(); // 往后端发数据 $.ajax({ url: "/ajax_add/", type: "get", data: {"i1": i1, "i2": i2}, success: function (arg) { {#alert(arg);#} // 把返回的结果填充到 id是i3的input框中 $("#i3").val(arg); } }) }); $("#b3").on("click", function () { // 点击 id是b1的按钮要做的事儿 var i1 = $("#i1").val(); var i2 = $("#i2").val(); // 找到页面上csrf_token // var csrfToken = $("[name='csrfmiddlewaretoken']").val(); // 往后端发数据 $.ajax({ url: "/ajax_add3/", type: "post", data: {"i1": i1, "i2": i2}, success: function (arg) { {#alert(arg);#} // 把返回的结果填充到 id是i3的input框中 $("#i3").val(arg); } }) }); $("#b2").on("click", function () { $.ajax({ url: "/test/", type: "get", success:function (a) { location.href = a; // alert(a); // 在页面上创建一个标签 //var imgEle = document.createElement("img"); //imgEle.src = a; // 把创建的img标签添加到文档中 //$("#b2").after(imgEle); } }) })
四、序列化
Django内置的serializers
def books_json(request): book_list = models.Book.objects.all()[0:10] from django.core import serializers ret = serializers.serialize("json", book_list) return HttpResponse(ret)
我们的数据中经常有日期时间,也就是datetime对象,而json.dumps是无法处理这样在类型的,那就需要通过自定义处理器来做扩展,如下:
class JsonCustomEncoder(json.JSONEncoder): """ 自定义一个支持序列化时间格式的类 """ def default(self, o): if isinstance(o, datetime): return o.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(o, date): return o.strftime("%Y-%m-%d") else: return json.JSONEncoder.default(self, o) def books_json(request): book_list = models.Book.objects.all().values_list("title", "publish_date") ret = json.dumps(list(book_list), cls=JsonCustomEncoder) return HttpResponse(ret)
五、补充一个SweetAlert插件示例
https://github.com/lipis/bootstrap-sweetalert 下载sweetalert 插件
$(".btn-danger").on("click", function () { swal({ title: "你确定要删除吗?", text: "删除可就找不回来了哦!", type: "warning", showCancelButton: true, confirmButtonClass: "btn-danger", confirmButtonText: "删除", cancelButtonText: "取消", closeOnConfirm: false }, function () { var deleteId = $(this).parent().parent().attr("data_id"); $.ajax({ url: "/delete_book/", type: "post", data: {"id": deleteId}, success: function (data) { if (data.status === 1) { swal("删除成功!", "你可以准备跑路了!", "success"); } else { swal("删除失败", "你可以再尝试一下!", "error") } } }) }); })