Mark's blog

Content



该系列文章源码来自: 博主第一次手撸博客(Django)
温馨提示: 该系列教程不提供前端布局和美化方面的内容, 博主本行是后端, 在我的项目中前端部分采用的框架是 Materialize, 是谷歌 Material Design 设计风格的前端框架, 欲知详情请点击上方提供的仓库地址, 源码采用WTFPL许可证开源


开发环境

  • 操作系统: Manjaro Linux 18
  • Python版本: Python3

    提示: Manjaro把Python3作为默认的Python版本, 其他发行版可能默认版本是Python2, 如果默认为Python2, 以下出现的Python和pip命令请使用python3和pip3

  • Django版本: v2.1.5
  • jQuery版本: v3.3.1

HTML部分

1
2
3
4
5
6
7
8
9
10
<form class="col s-12" id="login-form">
<input type="text" id="username" maxlength="8" required onchange="isEmpty()">
<label for="username">用户名</label>

<input type="password" id="password" maxlength="16" required onchange="isEmpty()">
<label for="password">密码</label>

<button type="button" id="login-button">登录</button>
<button type="reset">重置</button>
</form>

onchang="isEmpty()" 是本篇文章的彩蛋, 欲知详情下篇揭晓


js部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
document.getElementById('login-button').onclick = function () {
$.ajax({
type: "POST",
url: "/login_api/",
data: {
username: $("#username").val(),
password: $("#password").val()
},
dataType: "json",
success: function (data) {
if (data.status === '1') {
alert('登录成功');
window.location.href=document.referrer||host + "";
}
else if (data.status === '0') {
alert('很显然你正在做一些不该做的事情')
}
},
error: function (jpXHR) {
alert("Status Code: " + jpXHR.status);
},
});
};

首先我要说的是, 有些人一看, 你这为什么用 getElementById 这种原生js写法, 你看你用jQuery的选择器多简单, $('#login-button') 多简洁. 我也想啊T_T, 本来是用的jQuery元素选择器, 无论我把jQuery的文件放在 <head>, <body>尾部, 还有清空了好几次浏览器缓存, 它就是点了button之后没反应, 这种写法是经n次实践成功了的, so, 外在形式是多样的, 其中的意思你们肯定是懂的

后期吐槽: 第二版源码中, $('#login-button').click(function() {});的标准jQuery写法完全没问题.

  • onclick: 监听 click 事件
  • $.ajax(): 使用jQuery封装的ajax方法 (原生js的代码量会比较大, 但是便于初学者理解整个流程, 廖雪峰老师的讲解)
  • type: 请求方式, 使用较多的有 POSTGET
  • url: 向后端发送请求的(API)地址
  • data: 发送的数据, {xxx: xxx, xxx: xxx} 是 json 数据格式的写法
  • dataType: 后端服务器(实际就是API函数)处理完数据后, 会返回数据到前端, 这里就是设置要接收的返回数据的类型
  • success: 在发送成功的情况下, 自定义要做的操作, 注意了, data 关键字再次出现, 道理其实很简单, 我们把打包好的一个json数据发过去了, 后端API处理成功, 返回一个数据, 那么 data 关键字会自动接收而且变成这个后端API返回的数据, 接着我们对返回的数据做一点点处理去显示出我们想要的效果.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    if user is not None and user.is_active:
    login(request, user)
    return JsonResponse({
    "status": '1',
    "message": '登录成功'
    })
    else:
    return JsonResponse({
    "status": '0',
    "message": '登录失败'
    })

这就是我们后端API通过 JsonResponse 方法向前端返回一个json数据的代码片段(在Python中以字典形式表示, 所以 key 是要打引号表示字符串)

  • error: 即发送不成功, 以上的error处理函数可以当做一个固定写法. 403 Forbidden 就是服务器拒绝此次请求, 500 Server Error 就是服务器连不上了.

以上就是在Django框架中使用Ajax的基本操作了


使用 FormData 对象打包数据

  • 参考资料: MDN - FormData 对象的使用

    注: MDN 是查询前端知识非常好的网站, 强烈推荐使用, 在这次项目中多次得到MDN的帮助, 用户体验很好

1
2
3
4
5
6
7
// 比如说我要一次性上传多张图片, 要把这些图片打包在一起
var files = document.querySelector('input[type=file]').files;
var formFile = new FormData();

for (let i = 0; i < files.length; i++) {
formFile.append("image", files[i]); // 主要使用 append 方法添加数据
}
  • 那么在下面的Ajax方法里定义data为上面的formFile变量(即FormData对象)即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$.ajax({
type: 'POST',
url: '/image_upload_api/',
data: formFile,
dataType: 'json', // 设置预期的服务器返回的数据类型
cache: false,
contentType: false,
processData: false, // 不处理表单数据, 在上传图片时需要加上
success: function (data) {
if (data.status === "OK") {
var message = "上传成功. 是否跳转到图库?";
if (confirm(message) === true) {
window.location.href = '/gallery_page/';
}
else {
window.location.reload();
}
}
else if (data.status === "WTF") {
alert("Create objects error");
}
},
error: function (jpXHR) {
alert("Status Code: " + jpXHR.status);
},
});

看了这些基础内容, 相信大家可以举一反三了

 评论