urs.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r\'^admin/\', admin.site.urls),
url(r\'^$\',views.index),
url(r\'^upload_file/$\',views.upload_file)
]
views.py
from django.shortcuts import render,HttpResponse
from app01 import models
from django.http import JsonResponse
# Create your views here.
def index(request):
return render(request,\'index.html\')
def upload_file(request):
\'\'\'文件上传\'\'\'
import json
dic = {\'status\':100,\'msg\':None}
if request.method == \'POST\':
# post形式上传json格式数据,POST中没有值,在body中取出
upload_dic = json.loads(request.body)
name = upload_dic[\'name\']
pwd = upload_dic[\'pwd\']
user = models.User.objects.filter(name=name,pwd=pwd).first()
if user:
dic[\'msg\'] = \'登陆成功\'
else:
dic[\'status\'] = 101
dic[\'msg\'] = \'账号或密码错误\'
# 这里注意返回一定是Json格式返回
return JsonResponse(dic)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
<script src="/static/jquery.js"></script>
<title>ajax</title>
</head>
<body>
<h1>Ajan实现json格式的数据传输</h1>
<p>用户名:<input type="text" name="\'name" id="name"></p>
<p>密码:<input type="password" name="pwd" id="pwd"></p>
<button id="btn2">点击登录</button>
<span id="errors"></span>
</body>
<script>
$("#btn2").click(function () {
var upload_data = {name:$(\'#name\').val(),pwd:$(\'#pwd\').val()}
{#js语法把字典格式转成json格式字符串#}
var upload_json = JSON.stringify(upload_data)
{#js语法把json字符串转成原生的格式#}
{#var json_parse = JSON.parse(upload_data)#}
$.ajax({
url: \'/upload_file/\',
type: \'post\',
contentType: \'application/json\', //指定格式为json格式
data: upload_json,
success: function (data) {
console.log(data)
if (data.status==100){
location.href = \'http://www.baidu.com\'
}else{
$(\'#errors\').text(data.msg)
}
}
})
})
</script>
</html>