Ajax-get

url

    url(r'^ajax_add/', views.ajax_add),
url(r'^ajax_demo1/', views.ajax_demo1),

视图

def ajax_demo1(request):
return render(request, "ajax_demo1.html") def ajax_add(request):
i1 = int(request.GET.get("i1"))
i2 = int(request.GET.get("i2"))
ret = i1 + i2
return JsonResponse(ret, safe=False)

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AJAX局部刷新实例</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="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
$("#b1").on("click", function () {
$.ajax({
url:"/ajax_add/",
type:"GET",
data:{"i1":$("#i1").val(),"i2":$("#i2").val()},
success:function (data) {
$("#i3").val(data);
}
})
})
</script>
</body>
</html>

Ajax-post

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试AJAX的data参数</title>
</head>
<body> <button id="b1">点我</button> <input type="text" id="i1">
<span></span> <hr>
<div>111</div>
<div>222</div>
<div>333</div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="/static/setupAjax.js"></script>
<script>
$("#b1").click(function () {
// 先根据name 找到那个隐藏的input标签
var csrfToken = $("[name='csrfmiddlewaretoken']").val();
// 给/oo/发送AJAX请求
$.ajax({
url: '/oo/',
type: 'POST',
data: {
"name": "alex",
"hobby": JSON.stringify(["抽烟", "喝酒", "吹牛逼"]),
// "csrfmiddlewaretoken": csrfToken
},
success:function (res) {
console.log(res);
// 反序列化
// var ret = JSON.parse(res); 如果后端使用JsonResponse 返回响应,前端JS就不需要再反序列化
if (res.code !== 0){
console.log(res.err);
} else {
console.log(res.msg);
} }
})
});
var $i1 = $("#i1");
// 给 i1 标签绑定一个失去焦点的事件
$i1.on("input", function () {
// this --> 触发当前事件的DOM对象
// 1. 取到用户输入的用户名
var username = $(this).val();
var _this = this;
// 2. 发送到后端
$.ajax({
url: '/check/',
type: 'get',
data: {"username": username},
success:function (res) {
console.log(res);
if (res.code !== 0){
// 表示用户名已经存在
$(_this).next().text(res.msg).css("color", "red")
}
}
})
// 3. 根据响应的结果做操作
}); // 给 i1 标签绑定一个获取焦点的事件
$i1.focus(function () {
$(this).next().text("");
}) </script> </body>
</html>

要引入的文件

/*
* 此文件一用于判断 ajax请求是不是非安全请求,如果是就在请求头中设置csrf_token
* */ // 定义一个从Cookie中根据name取值的方法
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
// 调用上面的方法,从cookie中取出csrftoken对应的值
var csrftoken = getCookie('csrftoken'); //
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
} $.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});

js文件

Ajax-post-upload

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body> <form action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" id="f1">
<input type="submit" value="提交">
<button id="b1" type="button">点我</button>
</form> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="/static/setupAjax.js"></script> <script>
$("#b1").click(function () {
// 创建一个FormData对象
var obj = new FormData();
// 将要上传的文件数据添加到对象中
obj.append("file", document.getElementById("f1").files[0]);
obj.append("name", "alex");
$.ajax({
url: "/upload/",
type: "post",
processData: false, // 不让jQuery处理我的obj
contentType: false, // 不让jQuery设置请求的内容类型
data: obj,
success:function (res) {
console.log(res);
}
}) })
</script>
</body>
</html>

视图

# 上传文件测试
def upload(request):
if request.method == "POST":
# 从请求中取上传的文件数据
file_obj = request.FILES.get("file")
filename = file_obj.name with open(filename, "wb") as f:
for chunk in file_obj.chunks():
f.write(chunk)
return render(request, "upload.html")

最新文章

  1. Duilib源码分析(四)绘制管理器—CPaintManagerUI
  2. javascript 判断为true false
  3. win8.1 Framework3.5安装不上的问题
  4. 记一次python编码错误
  5. Shmget 参数 0600的解释
  6. 阅读《LEARNING HARD C#学习笔记》知识点总结与摘要一
  7. 【读书笔记】iOS-使用应用内支付注意事项
  8. 移动网页版Meta 标签
  9. MPICH3环境配置
  10. CentOS7安装最新版git教程
  11. tensorFlow入门实践(三)初识AlexNet实现结构
  12. AIOps指导
  13. 数据库的IO and 数据库优化问题
  14. [error] 2230#2230: *84 client intended to send too large body: 1711341 bytes
  15. linux新手向-文件的权限及修改
  16. 给ajax表单提交数据前面加上实体名称
  17. 聊一聊Linux中的工作队列
  18. Linux磁盘管理,vi编辑器以及包管理器
  19. phoenix错误
  20. AOP-Pointcut-笔记

热门文章

  1. Scratch运动模块——有趣的弹球游戏(一)
  2. 谷歌(Google)学术镜像,谷歌镜像
  3. Python 的 Mixin 类(转)
  4. hdu 3342 拓扑模板题
  5. 清空windows系统网络配置
  6. DRF 01
  7. java玩转zip压缩包
  8. Centos7 配置 svn服务端
  9. mimikatz记录
  10. 【转载】Android性能优化之渲染篇