一.Ajax简介

  AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。

AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)

优点: ​ AJAX使用Javascript技术向服务器发送异步请求 ​ AJAX无须刷新整个页面

ajax基本语法:

     $.ajax({
url:'/index/',
type:'get',
date:{"name":"shy","pwd":123},
success:function(response){
console.log(response)
}
})

应用案例:判断用户名是否已经被注册

二.文件上传

1.请求头contentType:contentType是指请求体的数据封装格式,常见的类型有三种

(1).application/x-www-form-urlencoded ​ 此类型是from表单默认的类型,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。 ​ 请求类似于下面这样(无关的请求头在本文中都省略掉了): ​ POST http://www.example.com HTTP/1.1 ​ Content-Type: application/x-www-form-urlencoded;charset=utf-8 ​ user=yuan&age=22 ​ (2).multipart/form-data ​ 这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 <form> 表单的 enctype 等于 multipart/form-data。 ​ 直接来看一个请求示例:

 POST http://www.example.com HTTP/1.1
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA ------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="user" yuan
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

(3).application/json ​ 现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。 ​ 由于 JSON 规范的流行,除了低版本 IE 之外的各大浏览器都原生支持 JSON.stringify, ​ 服务端语言也都有处理 JSON 的函数,使用 JSON 不会遇上什么麻烦。

2.contentType的查看方式

当前端有一个简单的form表单:

 <form action="/text/" method="post">
{% csrf_token %}
姓名<input name="name" type="text">
年龄<input name="age" type="text">
<button>提交</button>
</form>

后端对应一个相应的处理函数:

 def text(request):
print(request.POST)
return HttpResponse('ok')

运行成功后,我们可以从浏览器的请求头中看到:

 Content-Type: application/x-www-form-urlencoded

3.基于form表单的文件上传

在模板中:

 <form action="/byform/" method="post" enctype="multipart/form-data">
{% csrf_token %}
姓名<input name="user" type="text"><br>
请选择文件 <input name="file" type="file"><br>
<button>提交</button>
</form>

在视图中:

 def byform(request):
print(request.POST)
# < QueryDict: {'csrfmiddlewaretoken': ['9BxiKXnDy4xobLQ9m4QZDHQsOJeiWcCCE0uETorZjgCRZB01oL9evgqBULX2ERY2'],'user': ['alex']} > print(request.FILES)
# < MultiValueDict: {'file': [ < InMemoryUploadedFile: IMG20181030152136.jpg(image / jpeg) >]} > # 文件对象
file_obj=request.FILES.get('file') # 文件对象的name属性,获取文件名称
file_name=file_obj.name
# IMG20181030152136.jpg path=os.path.join(BASE_DIR,'media','img',file_name)
with open(path,'wb') as f:
for line in file_obj:
f.write(line)
return HttpResponse('上传成功')

4.基于ajax的文件上传

在模板中

 <h4>基于ajax的文件上传</h4>
<form >
姓名 <input class="num3" name="user" type="text"><br>
文件 <input class="num4" type="file">
<input type="button" class="btn1" value="提交">
</form> $('.btn1').click(function(){
var formdata=new FormData();
formdata.append("num3",$('.num3').val());
formdata.append("num4",$('.num4')[0].files[0]); $.ajax({
url:'/byform/',
type:'post',
processData: false , // 不处理数据
contentType: false,
data:formdata,
headers:{"X-CSRFToken":$.cookie('csrftoken')},
success:function(response){
console.log(response)
},
})
})

在视图中

 def byform(request):
print(request.POST)
# < QueryDict: {'csrfmiddlewaretoken': ['9BxiKXnDy4xobLQ9m4QZDHQsOJeiWcCCE0uETorZjgCRZB01oL9evgqBULX2ERY2'],'user': ['alex']} >
print(request.FILES)
# < MultiValueDict: {'file': [ < InMemoryUploadedFile: IMG20181030152136.jpg(image / jpeg) >]} >
# 文件对象
file_obj=request.FILES.get('num4')
# 文件对象的name属性,获取文件名称 file_name=file_obj.name
# IMG20181030152136.jpg path=os.path.join(BASE_DIR,'media','img',file_name)
with open(path,'wb') as f:
for line in file_obj:
f.write(line)
return HttpResponse('上传成功')

三.分页器

1.批量导入数据

 for i in range(100):
book=Book(title="悼念金庸-%s"%i,price=i*i,pub_date='2012-12-12',publish_id=1 )
list.append(book)
Book.objects.bulk_create(list)

2.分页器语法

         paginator=Paginator(book_list,20)
print(paginator.count) #一共有多少页
print(paginator.num_pages) #分了多少页
print(paginator.page_range) #每一页的页码
page=paginator.page(5) #第n页的数据
# for i in page:
# print(i)
print(page.has_next()) #是否有上一页
print(page.has_previous()) #是否有下一页
print(page.next_page_number()) #上一页的页码
print(page.previous_page_number()) #下一页的页码

3.实例

在模板中

             <div class="col-md-8 col-md-offset-2">
<nav aria-label="Page navigation">
<ul class="pagination">
{% if page.has_previous %}
<li><a href="?page={{ page.previous_page_number }}">上一页</a></li>
{% else %}
<li class="disabled"><span href="">上一页</span></li>
{% endif %} {% for num in paginator.page_range %} {% if num == page_num %}
<li class="active"><a href="?page={{ num }}">{{ num }}</a></li>
{% else %}
<li><a href="?page={{ num }}">{{ num }}</a></li>
{% endif %} {% endfor %} {% if page.has_next %}
<li><a href="?page={{ page.next_page_number }}">下一页</a></li>
{% else %}
<li class="disabled"><span href="">下一页</span></li>
{% endif %}
</ul>
</nav>
</div>

在视图中

             paginator = Paginator(book_list, 20)
page_num=int(request.GET.get("page",1) ) #如果取不到,就用1
page=paginator.page(page_num)
return render(request,'index.html',{"book_list":book_list,"paginator":paginator,"page":page,"page_num":page_num})

功能实现的函数:

         class Pagination():
def __init__(self, current_page_num, all_count, request, per_page_num=5, pager_count=11):
"""
封装分页相关数据
:param current_page_num: 当前访问页的数字
:param all_count: 分页数据中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数
"""
try:
current_page_num = int(current_page_num)
except Exception as e:
current_page_num = 1
if current_page_num < 1:
current_page_num = 1
self.current_page_num = current_page_num
self.all_count = all_count
self.per_page_num = per_page_num
all_pager, tmp = divmod(all_count, per_page_num)
if tmp:
all_pager += 1
self.all_pager = all_pager
self.pager_count = pager_count
self.page_count_half = int((pager_count - 1) / 2)
import copy
self.params = copy.deepcopy(request.GET) @property
def start(self):
return int((self.current_page_num - 1) * self.per_page_num) @property def end(self):
return int(self.current_page_num * self.per_page_num) def page_html(self):
if self.all_pager<=self.pager_count:
page_start=1
page_end=self.all_pager+1
else:
if self.current_page_num<=self.page_count_half:
page_start=1
page_end=self.pager_count+1
else:
if self.current_page_num >(self.all_pager-self.page_count_half):
page_start=self.all_pager-self.pager_count+1
page_end=self.all_pager+1
else:
page_start=self.current_page_num-self.page_count_half
page_end=self.current_page_num+self.page_count_half+1
page_html_list=[]
first_page='<li><a href="?page=%s">首页</li>' % 1
page_html_list.append(first_page)
if self.current_page_num<=1:
prev_page="<li class='disabled'><a href='#'>上一页</a></li>"
else:
prev_page = "<li ><a href='?page=%s'>上一页</a></li>" % (self.current_page_num-1)
page_html_list.append(prev_page)
for i in range(page_start,page_end):
self.params["page"]=i
if i==self.current_page_num:
temp="<li class='active'><a href='?%s'>%s</a></li>" % (self.params.urlencode(),i)
else:
temp = "<li><a href='?%s'>%s</a></li>" % (self.params.urlencode(), i)
page_html_list.append(temp)
if self.current_page_num>=self.all_pager:
next_page="<li class='disabled'><a href='#'>下一页</a></li>"
else:
next_page = "<li ><a href='?page=%s'>下一页</a></li>" % (self.current_page_num+1)
page_html_list.append(next_page)
last_page = '<li><a href="?page=%s">尾页</li>' % (self.all_pager)
page_html_list.append(last_page)
return "".join(page_html_list)

ajax,文件上传,分页器的更多相关文章

  1. AJAX文件上传实践与分析,带HTML5文件上传API。

    对于HTML5已经支持AJAX文件上传了,但如果需要兼容的话还是得用一点小技巧的,HTML5等等介绍,先来看看以前我们是怎么写的. 网上可能会有一些叫AJAX文件上传插件,但在AJAX2.0之前是不可 ...

  2. 兼容ie的jquery ajax文件上传

    Ajax文件上传插件很多,但兼容性各不一样,许多是对ie不兼容的,另外项目中是要求将网页内容嵌入到桌面端应用的,这样就不允许带flash的上传插件了,如:jquery uploadify...悲剧 对 ...

  3. jQuery插件AjaxFileUpload实现ajax文件上传

    转自:http://www.cnblogs.com/linjiqin/p/3530848.html jQuery插件AjaxFileUpload用来实现ajax文件上传,该插件使用非常简单,接下来写个 ...

  4. ajax 文件上传,ajax

    ajax 文件上传,ajax 啥也不说了,直接上代码! <input type="file" id="file" name="myfile&qu ...

  5. 转: 如何实现jQuery的Ajax文件上传

    [PHP文件上传] 在开始之前,我觉得是有必要把通WEB上传文件的原理简单说一下的.实际上,在这里不管是PHP,JSP,还是ASP处理上传的文件,其实都是WEB早已把文件上传到服务器了,我们只是运用上 ...

  6. [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传

    原文 [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件 ...

  7. php+ajax文件上传

    php+ajax文件上传 html: <input id="user_real_name" class="input_show" type="t ...

  8. springmvc+ajax文件上传

    环境:JDK6以上,这里我是用JDK8,mysql57,maven项目 框架环境:spring+springmvc+mybaits或spring+springmvc+mybatis plus 前端代码 ...

  9. iframe实现Ajax文件上传效果示例

    <!doctype html> <html> <head> <meta charset=utf-8> <head> <title> ...

随机推荐

  1. 数据访问层之Repository

    数据访问层之Repository   接上文 项目架构开发:数据访问层之Logger 本章我们继续IRepository开发,这个仓储与领域模式里边的仓储有区别,更像一个工具类,也就是有些园友说的“伪 ...

  2. cordova使用cordova-plugin-baidumaplocation插件获取定位

    原文:cordova使用cordova-plugin-baidumaplocation插件获取定位 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/m ...

  3. Qt 自定义事件(三种方法:继承QEvent,然后Send Post就都可以了,也可以覆盖customEvent函数,也可覆盖event()函数)

    Qt 自定义事件很简单,同其它类库的使用很相似,都是要继承一个类进行扩展.在 Qt 中,你需要继承的类是 QEvent. 继承QEvent类,你需要提供一个QEvent::Type类型的参数,作为自定 ...

  4. 工作流管理平台Airflow

    Airflow 1. 引言 Airflow是Airbnb开源的一个用Python写就的工作流管理平台(workflow management platform).在前一篇文章中,介绍了如何用Cront ...

  5. 绑定到异步的ObservableCollection

    原文:绑定到异步的ObservableCollection 在进行WPF开发过程中,需要从一个新的线程中操作ObservableCollection,结果程序抛出一个NotSupportedExcep ...

  6. The bundle does not contain an app icon for iPhone / iPod Touch of exactly &#39;120x120&#39; pixels, in .pn

    xcode 6.3 载发生时的应用'Missing recommended icon file - The bundle does not contain an app icon for iPhone ...

  7. crossplatform----文本编辑器工具Atom安装

    1.简介 Atom 是 Github 专门为程序员推出的一个跨平台文本编辑器.具有简洁和直观的图形用户界面,并有很多有趣的特点:支持CSS,HTML,JavaScript等网页编程语言.它支持宏,自动 ...

  8. NS2网络模拟(1)-延迟

    1: #NS2_有线部分\EndDelay.awk 2: 3: BEGIN { 4: #Initialize the variable 5: MaxID = 0; 6: i = 0; 7: } 8: ...

  9. WPF - 善用路由事件

    原文:WPF - 善用路由事件 在原来的公司中,编写自定义控件是常常遇到的任务.但这些控件常常拥有一个不怎么好的特点:无论是内部还是外部都没有使用路由事件.那我们应该怎样宰自定义控件开发中使用路由事件 ...

  10. PHP模拟POST提交数据并获得返回值之CURL方法(使用PHP extension,然后使用php_curl.dll,很不错)

    今天公司做个东西,需要条用同事的接口,我的代码和他的代码不在同一个域下,但是都是子域. a.ifensi.com与b.ifensi.com的关系. 我需要传递一个关联数组过去,他那边给我返回一个jso ...