简介:

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

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

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

Ajax

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

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

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

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

views.py

 #coding:utf8
from django.shortcuts import render,HttpResponse,render_to_response def Ajax(request):
if request.method=='POST':
print request.POST return HttpResponse('执行成功')
else:
return render_to_response('app03/ajax.html')

ajax.html

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<input id='name' type='text' />
<input type='button' value='点击执行Ajax请求' onclick='DoAjax()' /> <script src='/static/jquery/jquery-3.2.1.js'></script>
<script type='text/javascript'>
function DoAjax(){
var temp = $('#name').val();
$.ajax({
url:'app03/ajax/',
type:'POST',
data:{data:temp},
success:function(arg){
console.log(arg);
},
error:function(){
console.log('failed')
}
});
}
</script>
</html>

运行,结果:

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

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

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

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<input id='name' type='text' />
<input type='button' value='点击执行Ajax请求' onclick='DoAjax()' /> <script src='/static/jquery/jquery-3.2.1.js'></script>
<script type='text/javascript'>
function DoAjax(){
var temp = $('#name').val();
$.ajax({
url:'app03/ajax/',
type:'POST',
data:{data:temp},
success:function(arg){
var obj=jQuery.parseJSON(arg);
console.log(obj.status);
console.log(obj.msg);
console.log(obj.data);
$('#name').val(obj.msg);
},
error:function(){
console.log('failed')
}
});
}
</script>
</html>

views.py

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

打印数据样式:

jQuery Ajax 方法列表

 jQuery.get(...)
所有参数:
url: 待载入页面的URL地址
data: 待发送 Key/value 参数。
success: 载入成功时回调函数。
dataType: 返回内容格式,xml, json, script, text, html jQuery.post(...)
所有参数:
url: 待载入页面的URL地址
data: 待发送 Key/value 参数
success: 载入成功时回调函数
dataType: 返回内容格式,xml, json, script, text, html jQuery.getJSON(...)
所有参数:
url: 待载入页面的URL地址
data: 待发送 Key/value 参数。
success: 载入成功时回调函数。 jQuery.getScript(...)
所有参数:
url: 待载入页面的URL地址
data: 待发送 Key/value 参数。
success: 载入成功时回调函数。 jQuery.ajax(...) 部分参数: url:请求地址
type:请求方式,GET、POST(1.9.0之后用method)
headers:请求头
data:要发送的数据
contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
async:是否异步
timeout:设置请求超时时间(毫秒) beforeSend:发送请求前执行的函数(全局)
complete:完成之后执行的回调函数(全局)
success:成功之后执行的回调函数(全局)
error:失败之后执行的回调函数(全局) accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
dataType:将服务器端返回的数据转换成指定类型
"xml": 将服务器端返回的内容转换成xml格式
"text": 将服务器端返回的内容转换成普通文本格式
"html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
"script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
"json": 将服务器端返回的内容转换成相应的JavaScript对象
"jsonp": JSONP 格式
使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数 如果不指定,jQuery 将自动根据HTTP包MIME信息返回相应类型(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 converters: 转换器,将服务器端的内容根据指定的dataType转换类型,并传值给success回调函数
$.ajax({
accepts: {
mycustomtype: 'application/x-some-custom-type'
}, // Expect a `mycustomtype` back from server
dataType: 'mycustomtype' // Instructions for how to deserialize a `mycustomtype`
converters: {
'text mycustomtype': function(result) {
// Do Stuff
return newresult;
}
},
});

实现文件上传:

views.py

 from django.shortcuts import render,HttpResponse,render_to_response
import json,os,uuid def Upload(request):
if request.method=='POST':
id = str(uuid.uuid4())
ret = {'status':True,'data':None,'message':None}
obj = request.FILES.get('k3') file_path = os.path.join('static',id+obj.name)
f = open(obj.name,'wb')
for line in obj.chunks():
f.write(line)
f.close()
ret['data'] = file_path
return HttpResponse(json.dumps(ret))
else:
return render_to_response('appajax/put_file.html')

put_file.html

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传文件</title>
<style>
.log{
display: inline-block;
padding:5px 10px;
background-color:coral;
color: white;
}
</style>
</head>
<body>
<iframe style="display:none" id="ifrname1" name="ifra1"></iframe>
<form id="fm1" action="/appajax/put_file.html" method="post" enctype="multipart/form-data" target="ifra1">
<input type="file" name="k3" onchange="UploadFile();"/>
</form>
<h3>预览</h3>
<div id="preview"></div> <script src="/static/jquery/jquery-3.2.1.js"></script>
<script type="text/javascript">
function UploadFile(){
document.getElementById('iframe1').onload = ReloadIfrname();
document.getElementById('fm1').submit();
};
function ReloadIfrname(){
var content = this.contentWindow.document.body.innerHTML;
var obj = JSON.parse(content);
var tag = document.createElement('img');
tar.src = obj.data;
$('#preview').empty().append(tag);
};
</script>
</body>
</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. (转)OpenStack之服务端口号

    原文:https://blog.csdn.net/henulwj/article/details/47276391 在部署openstack的过程中,你会遇到配置各种服务的endpoint,opens ...

  2. Linux网络编程服务器模型选择之并发服务器(下)

    前面两篇文章(参见)分别介绍了循环服务器和简单的并发服务器网络模型,我们已经知道循环服务器模型效率较低,同一时刻只能为一个客户端提供服务,而且对于TCP模型来说,还存在单客户端长久独占与服务器的连接, ...

  3. Java reflect 反射 3 Class.forname

    Class.forName("xxx.xx.xx") 1 作用:加载类文件Class.forName(xxx.xx.xx) 返回的是一个类 而非对象 作用就是把对象的模板加载到内存 ...

  4. 关于对Enum的理解

    之前一直对枚举类型的理解存在误解,现重新学习 Enum 类型的介绍 枚举类型(Enumerated Type) 很早就出现在编程语言中,它被用来将一组类似的值包含到一种类型当中.而这种枚举类型的名称则 ...

  5. 关于Hall定理的学习

    基本定义 \(Hall\) 定理是二分图匹配的相关定理 用于判断二分图是否存在完美匹配 存在完美匹配的二分图即满足最大匹配数为 \(min(|X|,|Y|)\) 的二分图,也就是至少有一边的点全部被匹 ...

  6. 从零开始学JAVA(07)-使用SpringMVC4写helloworld

    一.关于开发环境 Eclipse IDE for Java EE Developers Jdk 1.7 (32位版本) SpringMVC 4.1.5.RELEASE apache-tomcat-7. ...

  7. [转]C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解

    本文转自:http://www.cnblogs.com/landeanfen/p/5501487.html 阅读目录 一.void无返回值 二.IHttpActionResult 1.Json(T c ...

  8. 初识DataGridView 表格数据控件

    DataGridView控件提供了一种强大而灵活的以表格形式显示数据的方式,用户可以使用DataGridView控件来显示少量数据的只读视图,也可以对其进行缩放以显示特大数据集的可编辑视图. 扩展Da ...

  9. Solr后台管理

    Solr web管理后台 访问主页:http://localhost:8080/solr/#/ 1. Dashboard 仪表盘,显示Solr的基本信息,包含solr版本,包含系统内存和jvm内存的使 ...

  10. [JAVA IDEA]在使用maven项目中,无法读取resources文件夹中的配置文件的一种解决方案

    1.在通过配置文件来连接数据库时,在resouces文件中放入了db.properties配置文件,但无法正常读取到 读取配置文件信息的代码: InputStream input=JdbcUtil.c ...