建设旅游业网站目的,客户网站建设洽谈方案,跑腿app开发,收录网站查询一、什么是JSON
1.介绍JSON独立于语言#xff0c;是一种与语言无关的数据格式。JSON指的是JavaScript对象表示法#xff08;JavaScript Object Notation#xff09;JSON是轻量级的文本数据交换格式JSON具有自我描述性#xff0c;更易理解JSON使用JavaScript语法来描述数据对… 一、什么是JSON
1.介绍JSON独立于语言是一种与语言无关的数据格式。JSON指的是JavaScript对象表示法JavaScript Object NotationJSON是轻量级的文本数据交换格式JSON具有自我描述性更易理解JSON使用JavaScript语法来描述数据对象但是JSON仍然独立于语言和平台。JSON解析器和JSON库支持许多不同的编程语言。2. Python中JSON操作import json1. json.dumps() -- 序列化 /json.dump() -- 文件操作 2. json.loads() -- 反序列化 /json.load() -- 文件操作3. JS中JSON操作1. JSON.stringify() -- 序列化2. JSON.parse() -- 反序列化
4. 例如合格的json对象[one, two, three]{ one: 1, two: 2, three: 3 }{names: [张三, 李四] }[ { name: 张三}, {name: 李四} ] 不合格的json对象{ name: 张三, age: 32 } // 属性名必须使用双引号[32, 64, 128, 0xFFF] // 不能使用十六进制值{ name: 张三, age: undefined } // 不能使用undefined{ name: 张三,birthday: new Date(Fri, 26 Aug 2011 07:13:10 GMT),getName: function() {return this.name;} // 不能使用函数和日期对象}5. 与XML的比较JSON 格式于2001年由 Douglas Crockford 提出目的就是取代繁琐笨重的 XML 格式。JSON 格式有两个显著的优点书写简单一目了然符合 JavaScript 原生语法可以由解释引擎直接处理不用另外添加解析代码。所以JSON迅速被接受已经成为各大网站交换数据的标准格式并被写入ECMAScript 5成为标准的一部分。XML和JSON都使用结构化方法来标记数据下面来做一个简单的比较。用XML表示中国部分省市数据如下 ?xml version1.0 encodingutf-8?countryname中国/nameprovincename黑龙江/namecitiescity哈尔滨/citycity大庆/city/cities/provinceprovincename广东/namecitiescity广州/citycity深圳/citycity珠海/city/cities/provinceprovincename台湾/namecitiescity台北/citycity高雄/city/cities/provinceprovincename新疆/namecitiescity乌鲁木齐/city/cities/province/country View Code 用JSON表示如下 {name: 中国,province: [{name: 黑龙江,cities: {city: [哈尔滨, 大庆]}}, {name: 广东,cities: {city: [广州, 深圳, 珠海]}}, {name: 台湾,cities: {city: [台北, 高雄]}}, {name: 新疆,cities: {city: [乌鲁木齐]}}]} View Code 由上面的两端代码可以看出JSON 简单的语法格式和清晰的层次结构明显要比 XML 容易阅读并且在数据交换方面由于 JSON 所使用的字符要比 XML 少得多可以大大得节约传输数据所占用得带宽二、AJAX简介
1、介绍AJAXAsynchronous Javascript And XML翻译成中文就是“异步的Javascript和XML”。即使用Javascript语言与服务器进行异步交互传输的数据为XML当然传输的数据不只是XML。AJAX 不是新的编程语言而是一种使用现有标准的新方法。AJAX 最大的优点是在不重新加载整个页面的情况下可以与服务器交换数据并更新部分网页内容。这一特点给用户的感受是在不知不觉中完成请求和响应过程AJAX 不需要任何浏览器插件但需要用户允许JavaScript在浏览器上执行。同步交互客户端发出一个请求后需要等待服务器响应结束后才能发出第二个请求异步交互客户端发出一个请求后无需等待服务器响应结束就可以发出第二个请求。2、AJAX常见应用情景 1.搜索引擎根据用户输入的关键字自动提示检索关键字。2.还有一个很重要的应用场景就是注册时候的用户名的查重。其实这里就使用了AJAX技术当文件框发生了输入变化时使用AJAX技术向服务器发送一个请求然后服务器会把查询到的结果响应给浏览器最后再把后端返回的结果展示出来。当输入用户名后把光标移动到其他表单项上时浏览器会使用AJAX技术向服务器发出请求服务器会查询你输入的用户名是否存在最终服务器返回true表示名你输入的用户名已经存在了浏览器在得到结果后显示“用户名已被注册”。整个过程中页面没有刷新只是局部刷新了在请求发出后浏览器不用等待服务器响应结果就可以进行其他操作3、AJAX的优缺点优点AJAX使用JavaScript技术向服务器发送异步请求AJAX请求无须刷新整个页面因为服务器响应内容不再是整个页面而是页面中的部分内容所以AJAX性能高 缺点 AJAX滥用对服务端压力比较大三、JS实现AJAX 1.注意一般我们都不使用原生的JS实现AJAX因为原生JS的步骤太繁琐(下面会介绍简单的AJAX实现)2. JS实现AJAX模板 var b2 document.getElementById(b2);b2.onclick function () {// 原生JSvar xmlHttp new XMLHttpRequest();xmlHttp.open(POST, /ajax_test/, true);xmlHttp.setRequestHeader(Content-type, application/x-www-form-urlencoded);xmlHttp.send(usernameq1mipassword123456);xmlHttp.onreadystatechange function () {if (xmlHttp.readyState 4 xmlHttp.status 200) {alert(xmlHttp.responseText);}};}; View Code
四、AJAX请求设置csrf_token
1、方式1
通过获取隐藏的input标签中的csrfmiddlewaretoken值放置在data中发送。$.ajax({url: /login/,type: POST,data: {username: xm,password: 123,csrfmiddlewaretoken: $([name csrfmiddlewaretoken]).val() // 使用jQuery取出csrfmiddlewaretoken的值拼接到data中},success: function (res) {console.log(res);}
}) View Code 2、方式2
通过获取返回的cookie中的字符串 放置在请求头中发送(需要引入一个jquery.cookie.js插件) $.ajax({url: /login/,type: POST,headers: {X-CSRFToken: $.cookie(csrftoken)}, // 从Cookie取csrftoken并设置到请求头中data: {username: xm, password: 123},success: function (res) {console.log(res);}
}) View Code 3、方式3
自己写一个getCookie方法
创建一个JS文件代码如下
(这是官网提供的代码) // 定义一个从本地获取Cookie的函数
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;
}
// 调用上面定义的函数从本地取出csrftoken对应的Cookie值
var csrftoken getCookie(csrftoken);function csrfSafeMethod(method) {// these HTTP methods do not require CSRF protectionreturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}$.ajaxSetup({beforeSend: function (xhr, settings) {if (!csrfSafeMethod(settings.type) !this.crossDomain) {// 给所有的AJAX请求设置请求头xhr.setRequestHeader(X-CSRFToken, csrftoken);}}
}); View Code 使用的时候只需要导入你这个JS代码ajxa请求就不需要自己手动添加csrf的值了注意方式3和方式2其实是同一种方法只是方式2是使用别人写好的插件方式3是自己写而已。如果使用从cookie中取csrftoken的方式需要确保cookie存在csrftoken值。如果你的视图渲染的HTML文件中没有包含 {% csrf_token %}Django可能不会设置CSRFtoken的cookie。这个时候需要使用ensure_csrf_cookie()装饰器强制设置Cookie。使用方式2和3需要在views.py的视图函数中加上这个装饰器确保浏览器中有cookie
django.views.decorators.csrf import ensure_csrf_cookieensure_csrf_cookie
def login(request):pass五、jQuery实现的AJAX
1、最基本的ajax
发送ajax请求
$.ajax({})参数url: 提交到哪个URL地址type: 提交的方式data: {你要发送的数据}success: function (res) {请求发送过去被正常响应后执行的函数res是后端返回来的数据}error: function (err) {请求发送过去响应失败时执行的函数}2、验证用户名是否存在的例子
1. models.py
class UserInfo(models.Model):username models.CharField(max_length12)password models.CharField(max_length20)2. HTML代码 !DOCTYPE html
html langzh-CN
headmeta http-equivcontent-type charsetutf-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1titleLogin/title
/headbodyplabel fori1用户名/labelinput typetext nameusername idi1span ids1 stylecolor: red;/span
/p{% csrf_token %}script srchttps://code.jquery.com/jquery-3.3.1.min.js/script
script typetext/javascript$(#i1).blur(function () {//输入框失去焦点时触发ajax请求$.ajax({url: /regirest/,type: POST,data: {username: $(#i1).val(), // 防止跨站伪造请求需要添加csrf_token的值csrfmiddlewaretoken: $([name csrfmiddlewaretoken]).val(),},success: function (res) {$(#s1).text(res)}})})
/script/body
/html View Code 3. views.pydef regirest(request):if request.method POST:username request.POST.get(username)is_exist UserInfo.objects.filter(usernameusername)if is_exist:return HttpResponse(用户名已存在)else:return HttpResponse(用户名可用)return render(request, regirest.html) View Code 3、用户登录例子
1. HTML代码 !DOCTYPE html
html langzh-CN
headmeta http-equivcontent-type charsetutf-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1titleLogin/title
/headbodydivh1欢迎登录/h1/div
divplabel fori1用户名/labelinput typetext idi1/pplabel fori2密码/labelinput typepassword idi2/ppbutton typebutton idb1登录/buttonspan stylecolor: red/span/p{% csrf_token %}
/divscript srchttps://code.jquery.com/jquery-3.3.1.min.js/script
script typetext/javascript$(#b1).click(function () {$.ajax({url: /login/,type: POST,data: {username: $(#i1).val(),pwd: $(#i2).val(),// 防止跨站伪造请求需要添加csrf_token的值csrfmiddlewaretoken: $([name csrfmiddlewaretoken]).val(),},success: function (res) {if (res.code 0){location.href res.next_url}else {// 有错误$(#b1span).text(res.err_msg)}}})})
/script/body
/html View Code 2. views.py class LoginView(views.View):def get(self, request):return render(request, login.html)def post(self, request):username request.POST.get(username)pwd request.POST.get(pwd)is_ok UserInfo.objects.filter(usernameusername, passwordpwd)res {code: 0} # 登录状态 0代表登录成功if is_ok:# 登录成功跳转到regirest页面res[next_url] /regirest/return JsonResponse(res)else:# 登录失败在页面上显示错误提示res[code] 1res[err_msg] 用户名或者密码错误return JsonResponse(res) View Code 4、上传文件例子
1. HTML代码!DOCTYPE html
html langen
headmeta http-equivcontent-type charsetutf-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1titleUpload/title
/head
body{% csrf_token %}h1上传文件/h1
div
input typefile idf1
button idb1 上传/button
/div
span stylecolor: red ids1/spanscript srchttps://code.jquery.com/jquery-3.3.1.min.js/script
script$(#b1).click(function () {// 取到要上传的文件数据存到一个对象中var fdObj new FormData();fdObj.append(xx, $(#f1)[0].files[0]);// 在请求的数据中添加csrftokrnvar csrfToken $([namecsrfmiddlewaretoken]).val();fdObj.append(csrfmiddlewaretoken, csrfToken);// 发ajax请求$.ajax({url: /upload/,type: post,data: fdObj,processData: false, // 告诉jQuery不要处理我上传的数据contentType: false, // 告诉jQuery不要设置请求的文件类型,这两个参数相当于enctypemultipart/form-datasuccess: function (res) {$(#s1).text(res);}})})
/script
/body
/html View Code 2.views.pyclass UploadView(views.View):def get(self, request):return render(request, upload.html)def post(self, request):file_obj request.FILES.get(xx)file_name file_obj.namewith open(file_name, wb) as f:for c in file_obj.chunks():f.write(c)return HttpResponse(上传成功) View Code 转载于:https://www.cnblogs.com/yidashi110/p/10091961.html