一.ajax介绍
1、ajax的含义
ajax全称“async javascript and xml”即:异步的javascript和xml。它是一种称谓,并不指代某项具体的技术,准确来说是一系列技术的集合.现在,所有的无刷新操作都被称为“ajax”.
2、使用ajax的好处:
使用ajax避免了整页数据的刷新,也减少了请求等待的时间,提高了用户体验.
二.ajax传参的两种格式
假设有如下表单,需要将这些表单用ajax传参的方式传给后台,该怎么做呢…
我们知道ajax传参的格式为$.post(“地址”,参数,function(返回值){}),套用这个格式进行传参,有以下两种方法:
方法一:提交表单中的部分字段
我们可以获取用户名,密码等内容,将其拼接成一个字典(想传什么就将其拼接成字典格式,没有特殊限制,你甚至可以单独的只传一个用户名),将其作为参数传给后台
例:
{‘username':username,‘password':password,‘csrfmiddlewaretoken':csrf}
或
{‘username':username‘}
或
{‘password':password}
关于csrf是预防跨站攻击的内容,你可以移步
接下来看看代码中是如何实现的,重点关注带有下方标记的代码
{# ajax #}
{# post提交 #}
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
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<!doctype html> <html lang= "en" > <head> <meta charset= "utf-8" > <title>注册</title> { # 引用jquery #} <script src= "https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js" ></script> </head> <body> <form ation= "" method= "post" > { # 防止跨站攻击 #} {% csrf_token %} 用户名:<input type= "text" name= "username" ><br> 密码:<input type= "text" name= "password" ><br> <!-- { # 表单提交 #}--> <!-- <input type= "submit" >--> <!-- { # ajax提交 #}--> <input type= "button" value= "注册" id= "button" > </form> </body> </html> <script> { # ajax #} $( "#button" ).click( function (){ username = $( "[name='username']" ).val(); password = $( "[name='password']" ).val(); csrf = $( "[type='hidden']" ).val(); console.log(username,password,csrf); { # post提交 #} { # $.post("地址",{参数},function(返回值){}) #} $.post( "/user/register/" ,{ 'username' :username, 'password' :password, 'csrfmiddlewaretoken' :csrf}, function (data){ console.log(data) }) }); </script> |
方法二:提交表单中的所有字段
console.log($(“form”).serialize()
serialize是把表单中的字段序列化,弄成get的请求的字符串格式,将其作为参数传给后台
值得注意的是这里就不能像方法一里那样想传什么参数就传什么参数了,而是表单中所有的字段都会被纳为请求的字符串格式
接下来看看代码中是如何实现的,重点关注带有下方标记的代码
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
27
28
29
30
31
32
33
34
35
36
|
<!doctype html> <html lang= "en" > <head> <meta charset= "utf-8" > <title>注册</title> { # 引用jquery #} <script src= "https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js" ></script> </head> <body> <form ation= "" method= "post" > { # 防止跨站攻击 #} {% csrf_token %} 用户名:<input type= "text" name= "username" ><br> 密码:<input type= "text" name= "password" ><br> <!-- { # 表单提交 #}--> <!-- <input type= "submit" >--> <!-- { # ajax提交 #}--> <input type= "button" value= "注册" id= "button" > </form> </body> </html> <script> { # ajax #} $( "#button" ).click( function (){ console.log($( "form" ).serialize()); { # post提交 #} { # $.post("地址",{参数},function(返回值){}) #} $.post( "/user/register/" ,console.log($( "form" ).serialize()), function (data){ console.log(data) }) }); </script> |
总结
到此这篇关于django学习之ajax post传参的文章就介绍到这了,更多相关django之ajax post传参内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!