json格式
合格的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;} // 不能使用函数和日期对象
}
stringify与parse
JSON.parse(): 用于将一个 JSON 字符串转换为 JavaScript 对象
eg:
console.log(JSON.parse('{"name":"Yuan"}'));
console.log(JSON.parse('{name:"Yuan"}')) ; // 错误
console.log(JSON.parse('[12,undefined]')) ; // 错误
JSON.stringify(): 用于将 JavaScript 值转换为 JSON 字符串。
eg: console.log(JSON.stringify({'name':"egon"})) ;
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1,5,"false"]'); // [1,"false"]
JSON.parse('null'); // null
JSON.parse('1'); // 1
Ajax
AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML)。
同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求; 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)
GET方式
url如下
url(r'^login/$',views.login ),url(r'^safly/$',views.safly ),
视图函数如下:
view.py
from django.shortcuts import render,redirect,HttpResponse,reverse
def login(request):
return render(request,"login.html")
def safly(request):
username = request.GET.get("username")
pwd = request.GET.get("pwd")
if username == "safly" and pwd == "123":
res = username + pwd
return HttpResponse(res)
login.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>Title</title>
<script src="/static/js/jquery-3.2.1.min.js"></script>
</head>
<body>
<input type="text">
<button id="id_btn">提交</button>
<script> $("#id_btn").click(function () { $.ajax({ url: "/safly/",type: "GET",data: {username: "safly",pwd: "123"},success: function (data) { console.log(data) } }) }) </script>
</body>
</html>
我们测试如下:
点击提交按钮,控制台输出
[30/Jan/2018 17:44:37] "GET /safly/?username=safly&pwd=123 HTTP/1.1" 200 8
浏览器输出
safly123
以上data改成data: {“username”: “safly”,pwd: “123”},也可以
会自动给转换成json格式的类型
POST方式
如果将上例中的type改成type: “POST”,
按着之前的流程会报错如下:
Forbidden (CSRF token missing or incorrect.): /safly/
我们需要进行添加csrf参数
login.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>Title</title> <script src="/static/js/jquery-3.2.1.min.js"></script> </head> <body> <input type="text" id="input_text"> <button id="id_btn">提交</button> {% csrf_token %} <script> $("#id_btn").click(function () { $.ajax({ url: "/safly/",type: "POST",data: { "username": "safly",pwd: "123",csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val() },success: function (data) { var data = JSON.parse(data) console.info(data.is_regist) if (data.is_regist) { $("#input_text").val("已经注册") } } }) }) </script> </body> </html>
views.py
from django.shortcuts import render,reverse
def login(request):
return render(request,"login.html")
def safly(request):
username = request.POST.get("username")
pwd = request.POST.get("pwd")
response={"is_regist":True}
if username == "safly" and pwd == "123":
pass
else:
response["is_regist"] = False
import json
response = json.dumps(response)
return HttpResponse(response)
或者如下的方式:
<script src="{% static 'js/jquery.cookie.js' %}"></script> $.ajax({ headers:{"X-CSRFToken":$.cookie('csrftoken')},})
$.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});
serialize序列化
不在标签内的表单控件不会被提交、没有name属性的表单控件不会被提交、带有disabled属性的表单控件不会被提交、没有被选中的表单控件不会被提交。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("div").text($("form").serialize()); }); }); </script>
</head>
<body>
<form action="">
First name: <input type="text" name="FirstName" value="Bill" /><br />
Last name: <input type="text" name="LastName" value="Gates" /><br />
</form>
<button>序列化表单值</button>
<div></div>
</body>
</html>
结果如下:
案例
先来看login页面
url(r'^login/$',views.login,name="login"),
from django.shortcuts import render,reverse
from . import models
def login(request):
return render(request,"login.html")
直接渲染login.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>Title</title> <script src="/static/js/jquery-3.2.1.min.js"></script> </head> <body> <p> <label for="name">姓名:<input type="text" name="name" id="name"></label> <span id="name_span"></span> </p> <p> <label for="pwd">密码:<input type="text" name="pwd" id="pwd"></label> <span id="pwd_span"></span> </p> <input type="button" value="注册" id="btn_sumit"> {% csrf_token %} <script> {##校验姓名#} $("#name").blur(function () { $.ajax({ url: "/validate/",data: {name: $("#name").val()},success: function (data) { var data = JSON.parse(data) console.info(data) if (data.is_regist) { {#已经注册#} $("#name_span").html(data.name + "已经注册").css("color","red") } else { {#没有注册#} $("#name_span").html(data.name + "可以使用").css("color","black") } } }) }) {#校验密码#} $("#btn_sumit").click(function () { $.ajax({ url: "/register/",data: { name: $("#name").val(),pwd: $("#pwd").val(),csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val() },success: function (data) { console.info(data) if(data == "ok"){ window.location.href="/index/"; //在同当前窗口中打开窗口 } } }) }) </script> </body> </html>
校验姓名
url(r'^validate/$',views.validate,name="validate"),
def validate(request):
my_name = request.GET.get("name")
user = models.User.objects.filter(name=my_name)
response_dic = {"name":my_name,"is_regist":False}
if user:
response_dic["is_regist"] = True
response_dic["name"] = user[0].name
import json
data = json.dumps(response_dic)
print(data)
#字符串
return HttpResponse(data)
注册利用ajax,不用form
url(r'^register/$',views.register,name="register"),url(r'^index/$',views.index,name="index"),
def register(request):
if request.method == "POST":
name = request.POST.get("name")
pwd = request.POST.get("pwd")
print(name,"------",pwd)
models.User.objects.create(name=name,pwd=pwd)
return HttpResponse("ok")
def index(request):
return render(request,"index.html")
原文链接:https://www.f2er.com/ajax/160436.html