Django——Ajax
1.Ajax概述对于WEB应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上。 对比1、传统的Web应用
2、Ajax AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种创建交互式网页应用的网页开发技术方案。
Ajax的特点:
Ajax的优点:
Ajax可以做:
2.基于jQuery的Ajax实现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 将自动替换 ? 为正确的函数名,以执行回调函数 ? 下面是一个基于jQueryAjax实现登录的demo 模板: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form id="form_login"> <input type="text" name="user" /> <input type="password" name="pwd" /> <span class="msg"></span> <input type="button" class="btn-primary" value="提交"> </form> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script> <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script> <script> $(".btn-primary").click(function(){ $.ajax({ url: "/login/",method: "post",data: $("#form_login").serialize(),dataType: "json",headers:{"X-CSRFtoken": $.cookie("csrftoken")},success: function(data){ if(data.status){ location.href="http://www.baidu.com" }else{ $(".msg").html(data.msg).css({"color":"red"}) } } }) }) </script> ? 视图: from django.http import JsonResponse def login(request): data = {"status":True,"msg": ‘‘} if request.method == "POST": user = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) if user == "root": if pwd == "mima": return JsonResponse(data) else: data["status"] = False data["msg"] = "密码错误" else: data["status"] = False data["msg"] = "用户名错误" return JsonResponse(data) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |