简介:

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

Ajax

  很多时候,我们在网页上请求操作时,不需要刷新页面。实现这种功能的技术就要Ajax!

jQuery中的ajax就可以实现不刷新页面就能向后台请求或提交数据的功能,现用它来做django中的ajax,所以先把jquey下载下来,版本越高越好。

一、ajax发送简单数据类型:

html代码:在这里我们仅发送一个简单的字符串

views.py

  1. #coding:utf8
  2. from django.shortcuts import render,HttpResponse,render_to_response
  3.  
  4. def Ajax(request):
  5. if request.method=='POST':
  6. print request.POST
  7.  
  8. return HttpResponse('执行成功')
  9. else:
  10. return render_to_response('app03/ajax.html')

ajax.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Ajax</title>
  6. </head>
  7. <body>
  8. <input id='name' type='text' />
  9. <input type='button' value='点击执行Ajax请求' onclick='DoAjax()' />
  10.  
  11. <script src='/static/jquery/jquery-3.2.1.js'></script>
  12. <script type='text/javascript'>
  13. function DoAjax(){
  14. var temp = $('#name').val();
  15. $.ajax({
  16. url:'app03/ajax/',
  17. type:'POST',
  18. data:{data:temp},
  19. success:function(arg){
  20. console.log(arg);
  21. },
  22. error:function(){
  23. console.log('failed')
  24. }
  25. });
  26. }
  27. </script>
  28. </html>

运行,结果:

二、ajax发送复杂的数据类型:

html代码:在这里仅发送一个列表中包含字典数据类型

由于发送的数据类型为列表 字典的格式,我们提前要把它们转换成字符串形式,否则后台程序接收到的数据格式不是我们想要的类型,所以在ajax传输数据时需要JSON

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Ajax</title>
  6. </head>
  7. <body>
  8. <input id='name' type='text' />
  9. <input type='button' value='点击执行Ajax请求' onclick='DoAjax()' />
  10.  
  11. <script src='/static/jquery/jquery-3.2.1.js'></script>
  12. <script type='text/javascript'>
  13. function DoAjax(){
  14. var temp = $('#name').val();
  15. $.ajax({
  16. url:'app03/ajax/',
  17. type:'POST',
  18. data:{data:temp},
  19. success:function(arg){
  20. var obj=jQuery.parseJSON(arg);
  21. console.log(obj.status);
  22. console.log(obj.msg);
  23. console.log(obj.data);
  24. $('#name').val(obj.msg);
  25. },
  26. error:function(){
  27. console.log('failed')
  28. }
  29. });
  30. }
  31. </script>
  32. </html>

views.py

  1. #coding:utf8
  2. from django.shortcuts import render,HttpResponse,render_to_response
  3. import json
  4.  
  5. # Create your views here.
  6. def Ajax(request):
  7. if request.method=='POST':
  8. print request.POST
  9. data = {'status':0,'msg':'请求成功','data':['11','22','33']}
  10. return HttpResponse(json.dumps(data))
  11.  
  12. else:
  13. return render_to_response('app03/ajax.html')

打印数据样式:

jQuery Ajax 方法列表

  1. jQuery.get(...)
  2. 所有参数:
  3. url: 待载入页面的URL地址
  4. data: 待发送 Key/value 参数。
  5. success: 载入成功时回调函数。
  6. dataType: 返回内容格式,xml, json, script, text, html
  7.  
  8. jQuery.post(...)
  9. 所有参数:
  10. url: 待载入页面的URL地址
  11. data: 待发送 Key/value 参数
  12. success: 载入成功时回调函数
  13. dataType: 返回内容格式,xml, json, script, text, html
  14.  
  15. jQuery.getJSON(...)
  16. 所有参数:
  17. url: 待载入页面的URL地址
  18. data: 待发送 Key/value 参数。
  19. success: 载入成功时回调函数。
  20.  
  21. jQuery.getScript(...)
  22. 所有参数:
  23. url: 待载入页面的URL地址
  24. data: 待发送 Key/value 参数。
  25. success: 载入成功时回调函数。
  26.  
  27. jQuery.ajax(...)
  28.  
  29. 部分参数:
  30.  
  31. url:请求地址
  32. type:请求方式,GETPOST1.9.0之后用method
  33. headers:请求头
  34. data:要发送的数据
  35. contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
  36. async:是否异步
  37. timeout:设置请求超时时间(毫秒)
  38.  
  39. beforeSend:发送请求前执行的函数(全局)
  40. complete:完成之后执行的回调函数(全局)
  41. success:成功之后执行的回调函数(全局)
  42. error:失败之后执行的回调函数(全局)
  43.  
  44. accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
  45. dataType:将服务器端返回的数据转换成指定类型
  46. "xml": 将服务器端返回的内容转换成xml格式
  47. "text": 将服务器端返回的内容转换成普通文本格式
  48. "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
  49. "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
  50. "json": 将服务器端返回的内容转换成相应的JavaScript对象
  51. "jsonp": JSONP 格式
  52. 使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
  53.  
  54. 如果不指定,jQuery 将自动根据HTTPMIME信息返回相应类型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string
  55.  
  56. converters 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数
  57. $.ajax({
  58. accepts: {
  59. mycustomtype: 'application/x-some-custom-type'
  60. },
  61.  
  62. // Expect a `mycustomtype` back from server
  63. dataType: 'mycustomtype'
  64.  
  65. // Instructions for how to deserialize a `mycustomtype`
  66. converters: {
  67. 'text mycustomtype': function(result) {
  68. // Do Stuff
  69. return newresult;
  70. }
  71. },
  72. });

实现文件上传:

views.py

  1. from django.shortcuts import render,HttpResponse,render_to_response
  2. import json,os,uuid
  3.  
  4. def Upload(request):
  5. if request.method=='POST':
  6. id = str(uuid.uuid4())
  7. ret = {'status':True,'data':None,'message':None}
  8. obj = request.FILES.get('k3')
  9.  
  10. file_path = os.path.join('static',id+obj.name)
  11. f = open(obj.name,'wb')
  12. for line in obj.chunks():
  13. f.write(line)
  14. f.close()
  15. ret['data'] = file_path
  16. return HttpResponse(json.dumps(ret))
  17. else:
  18. return render_to_response('appajax/put_file.html')

put_file.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>上传文件</title>
  6. <style>
  7. .log{
  8. display: inline-block;
  9. padding:5px 10px;
  10. background-color:coral;
  11. color: white;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <iframe style="display:none" id="ifrname1" name="ifra1"></iframe>
  17. <form id="fm1" action="/appajax/put_file.html" method="post" enctype="multipart/form-data" target="ifra1">
  18. <input type="file" name="k3" onchange="UploadFile();"/>
  19. </form>
  20. <h3>预览</h3>
  21. <div id="preview"></div>
  22.  
  23. <script src="/static/jquery/jquery-3.2.1.js"></script>
  24. <script type="text/javascript">
  25. function UploadFile(){
  26. document.getElementById('iframe1').onload = ReloadIfrname();
  27. document.getElementById('fm1').submit();
  28. };
  29. function ReloadIfrname(){
  30. var content = this.contentWindow.document.body.innerHTML;
  31. var obj = JSON.parse(content);
  32. var tag = document.createElement('img');
  33. tar.src = obj.data;
  34. $('#preview').empty().append(tag);
  35. };
  36. </script>
  37. </body>
  38. </html>

Django Ajax的使用的更多相关文章

  1. Django ajax MYSQL Highcharts<1>

    Another small project with django/Ajax/Mysql/Highcharts. 看下效果图  - delivery dashboard .嘿嘿 是不是还蛮好看的. 废 ...

  2. django ajax练习

    这几天遇到了django ajax请求出错的问题,总结一下 前端js:我这里创建的是一个字典格式的数据,前端js收到字典之后也是要用字典的形式去解包后台传送过来的数据,比如我下面的写法:data['s ...

  3. 关于Django Ajax CSRF 认证

    CSRF(Cross-site request forgery跨站请求伪造,也被称为“one click attack”或者session riding,通常缩写为CSRF或者XSRF,是一种对网站的 ...

  4. django ajax增 删 改 查

    具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...

  5. python学习-- Django Ajax CSRF 认证

    使用 jQuery 的 ajax 或者 post 之前 加入这个 js 代码:http://www.ziqiangxuetang.com/media/django/csrf.js /*======== ...

  6. django ajax 及批量插入数据 分页器

    ``` Ajax 前端朝后端发送请求都有哪些方式 a标签href GET请求 浏览器输入url GET请求 form表单 GET/POST请求 Ajax GET/POST请求 前端朝后端发送数据的编码 ...

  7. Django——Ajax

    1.Ajax简介 AJAX(Asynchronous Javascript And XML)--"异步的JavaScript与XML". Ajax使用Javascript语言与服务 ...

  8. django ajax提交form表单数据

    后台: from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts ...

  9. Django ajax提交 登录

    一.url from django.contrib import adminfrom django.urls import pathfrom appo1 import views urlpattern ...

  10. django ajax报错解决:You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set.

    Django版本号:1.11.15 django中ajax请求报错:You called this URL via POST, but the URL doesn't end in a slash a ...

随机推荐

  1. sql server 2008 R2 配置管理工具打不开

    使用 sql server 配置管理工具是报如下错误: 解决方法:   1 找出 sqlmgmproviderxpsp2up.mof 这个文件的位置   2 以管理员身份运行 mofcomp &quo ...

  2. springboot项目:Redis缓存使用

    保存Redis 第一步:启动类中加入注解 @EnableCaching package com.payease; import org.springframework.boot.SpringAppli ...

  3. idea中web.xml报错 Servlet should have a mapping

    配置springmvc时,报错,实际mapping已经写了,错误截图如下: 搜索无果,后来发现是工程的web.xml位置配置错误,因为我之前换过根目录位置. 修改方法: 打开Project Struc ...

  4. ../../build/debug/codegen/libCodeGen.a(llvm-codegen.cc.o ):( data.rel.ro_ZTIN4llvm18ValueMapCallbackVHIPKNS_5ValueENS_6WeakVHENS_14ValueMapConfigIS3_EEEE[_ZTIN4llvm18ValueMapCallbackVHIPKNS_5ValueENS_

    解决方式如下: wget http://llvm.org/releases/3.3/llvm-3.3.src.tar.gz    tar xvzf llvm-3.2.src.tar.gz    cd ...

  5. gcc对open(2)支持重载吗

    在Linux中,如果man -s2 open, 我们看到两种不同的函数原型声明: $ man -s2 open NAME open, creat - open and possibly create ...

  6. 深入redis内部--字典实现

    redis的字典定义和实现在dict.h和dict.c文件中. 1.字典结构 typedef struct dict { dictType *type; //定义了字典需要的函数 void *priv ...

  7. 哪些网站需要HTTPS(SSL证书)

    很多站长似乎不了解https站点是怎么回事,这就要从传统站点说起:传统的站点的http超文本传输协议,采用明文传输模式,存在着大量的灰色中 间环节,明文信息在中间代理服务器.路由器.wifi热点.通信 ...

  8. WCF中的AddressHeader作用

    客户端发送请求给服务端,服务端根据请求消息把消息转发给对应的终结点.这里面有个消息筛选机制,如果请求消息中带有地址报头相关信息,则会用地址报头匹配当前的所有终结点.所以默认情况下客户端和服务端的地址报 ...

  9. LINQ操作List<T>

    LINQ操作List<T>主要包括: 1.筛选 List<string> stcdList = stcdArray.ToList<string>() .FindAl ...

  10. C#构建树形数据结构

    转自:https://www.jb51.net/article/125747.htm 树形结构:最近在做任务管理,任务可以无限派生子任务且没有数量限制,前端采用Easyui的Treegrid树形展示控 ...