day71
## 1 ajax介绍
```python
# 1 异步 Javascript 和 XML:
-异步:跟同步是对应的
-javascript:通过javascript来操作,发送请求 ,到服务端
-xml:数据交互使用xml,现在主流使用json格式
-xml:可阅读性比较高,解析复杂,占的空间大
<name>lqz</name>
<age>19</age>
-json:可阅读性比较高,解析简单,占的空间小
{"name":"lqz","age":19}
-浏览器页面局部刷新(js的dom操作)
-通过js发送http的请求(go,java,php,requset)
# 2 同步和异步
#3 IAAS,PAAS,SAAS
# 4 同步交互和异步交互
同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
```
#
## 2 ajax的简单使用
```python
1 原生js写ajax请求(写起来很复杂,而且需要考虑浏览器版本)
2 jquery帮咱们封装好了一个方法 ajax,我们直接调用jquery的方法,就可以发送ajax的请求
3 后期,前后端分离了,还可以继续使用jquery的ajax, axios更主流一些
4 现在我们学的jquery的ajax方法的使用
5 需求:通过Ajax,实现前端输入两个数字,服务器做加法,返回到前端页面
6 模板
$.ajax({
url: '/add/',
method: 'post',
data:{'a':$("#first").val() ,'b':$("#second").val() },
success:function (data) {
//成功触发
},
error:function (error) {
//失败,触发
}
})
# 默认清空下ajax会把{'a':$("#first").val() ,'b':$("#second").val() }数据转成
# 预处理数据
a=20&b=30,放到body体中
# 编码默认用urlencoded
```
## 3 ajax上传文件
```python
1 http请求,body体中放文件内容,ajax本质就是发送http请求,所以它可以上传文件
2 两种上传文件的方式,form表单,ajax
3 固定模板
var formdata=new FormData()
formdata.append('myfile',$("#id_file")[0].files[0])
# 还可以带数据
$.ajax({
url:'/uploadfile/',
method: 'post',
//上传文件必须写这两句话
processData:false, # 预处理数据,
contentType:false, # 不指定编码,如果不写contentType,默认用urlencoded
data:formdata, # formdata内部指定了编码,并且自行处理数据
success:function (data) {
console.log(data)
}
})
```
## 4 ajax提交json格式
```python
$.ajax({
url:'/uploajson/', //写全,是什么样就写什么样
method:'post',
contentType: 'application/json',
//data要是json格式字符串
//data:'{"name":"","password":""}',
//把字典转成json格式字符串
//JSON.stringify(dic)
//把json格式字符串转成对象
//JSON.parse(data)
data:JSON.stringify({name:$("#id_name1").val(),password:$("#id_password1").val()}),
success:function (data) {
//返回字符串类型,需要转成js的对象,字典
//1 如果:django 返回的是HttpResponse,data是json格式字符串,需要自行转成字典
//2 如果:django 返回的是JsonResponse,data是就是字典
//ajax这个方法做的是,如果响应数据是json格式,自动反序列化
console.log(typeof data)
var res=JSON.parse(data)
console.log(typeof res)
console.log(res.status)
console.log(res.msg)
}
})
```
## 5 django内置序列化器(了解,不好用,后面有更好的)
```python
1 把对象转成json格式,json.dumps实现不了,
2 django内置了一个东西,可以把对象转成json格式
from django.core import serializers
book_list = Book.objects.all()
ret = serializers.serialize("json", book_list) # ret就是json格式字符串
ll=[]
for book in book_list:
ll.append({'name':book.name,'price':book.pirce})
import json
ret=json.dumps(ll)
return HttpResponse(ret)
```
index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="/static/jquery-3.3.1/jquery-3.3.1.min.js"></script> <title>Title</title> </head> <body> <input type="text" id="first">+<input type="text" id="second">=<input type="text" id="result"> <button id="btn">点我计算结果</button> <hr> <h1>通过form表单上传文件</h1> <form action="/uploadfile/" method="post" enctype="multipart/form-data"> <p><input type="file" name="myfile"></p> <p>用户名:<input type="text" name="name" ></p> <input type="submit" value="提交"> </form> <hr> <h1>通过ajax上传文件</h1> <p><input type="file" id="id_file"></p> <p>用户名:<input type="text" id="id_name"></p> <button id="btn_file">提交</button> <hr> <h1>通过ajax提交json格式数据</h1> <p>用户名:<input type="text" id="id_name1"></p> <p>密码:<input type="text" id="id_password1"></p> <p><button id="btn_json">提交</button></p> </body> <script> //使用原生js发送ajax请求(不讲,也不用看) //借助jquery封装好的ajax方法,发送ajax请求 //点击button按钮,触发ajax请求 $("#btn").click(function () { $.ajax({ url: '/add/', //向哪个地址发送请求 method: 'post', //发送什么请求 //使用jquery,获取输入框内的值 //向后端传输的数据(没有指定编码,默认使用urlencoded) data: {'a': $("#first").val(), 'b': $("#second").val()}, success: function (data) { //数据正常返回,就会触发该匿名函数的执行,返回的数据就会复制给data console.log(data) //把后端返回的数据,通过dom操作,写到input框中 $('#result').val(data) }, //请求失败,就会触发error的执行,并且把错误信息给error error: function (error) { console.log(error) } }) }) //ajax上传文件 $("#btn_file").click(function () { var formdata=new FormData() //实例化得到一个fromdata对象 //把文件放到对象内 //formdata.append('myfile',文件对象) formdata.append('myfile',$("#id_file")[0].files[0]) //问题:fomdata现在只放了一个文件对象,可不可以放数据?可以 //formdata.append('name','lqz') formdata.append('name',$("#id_name").val()) $.ajax({ url:'/uploadfile/', method: 'post', //上传文件必须写这两句话 processData:false, contentType:false, data:formdata, success:function (data) { alert(data) //console.log(data) //location.href='http://www.baidu.com' } }) }) //ajax提交json格式数据 $("#btn_json").click(function () { $.ajax({ url:'/uploajson/', //写全,是什么样就写什么样 method:'post', contentType: 'application/json', //data要是json格式字符串 //data:'{"name":"","password":""}', //把字典转成json格式字符串 //JSON.stringify(dic) //把json格式字符串转成对象 //JSON.parse(data) data:JSON.stringify({name:$("#id_name1").val(),password:$("#id_password1").val()}), success:function (data) { //返回字符串类型,需要转成js的对象,字典 //1 如果:django 返回的是HttpResponse,data是json格式字符串,需要自行转成字典 //2 如果:django 返回的是JsonResponse,data是就是字典 //ajax这个方法做的是,如果响应数据是json格式,自动反序列化 console.log(typeof data) var res=JSON.parse(data) console.log(typeof res) console.log(res.status) console.log(res.msg) } }) }) </script> </html>
# urls.py from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ # path('admin/', admin.site.urls), path('', views.index), path('add/', views.add), path('uploadfile/', views.uploadfile), path('uploajson/', views.uploajson), ]
# views.py from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return render(request, 'index.html') def add(request): # if request.is_ajax(): if request.method == 'POST': # 取出a和b a = int(request.POST.get('a')) b = int(request.POST.get('b')) print(a, b) # HttpResponse返回什么,js中的data就是什么(字符串) return HttpResponse(a + b) def uploadfile(request): file = request.FILES.get('myfile') name = request.POST.get('name') print(name) with open(file.name, 'wb') as f: for line in file: f.write(line) return HttpResponse('上传成功') from django.http import JsonResponse def uploajson(request): data = request.body print(data) dic = {'status': 100, 'msg': '成功'} print(request.POST) # 有数据?没有 import json # return HttpResponse(json.dumps(dic)) return JsonResponse(dic) # 内部设置了编码

浙公网安备 33010602011771号