Django - Ajax - 参数
一、Jquery实现Ajax
url type data success error complete statusCode
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{% static 'JS/jquery-3.1.1.js' %}"></script>
</head>
<body>
<button class="send_Ajax">send_Ajax</button>
<script>
//$.ajax的两种使用方式:
//$.ajax(settings);
//$.ajax(url,[settings]);
$(".send_Ajax").click(function(){
$.ajax({
url:"/handle_Ajax/",
type:"POST",
data:{username:"Yuan",password:123},
success:function(data){
alert(data)
},
//=================== error============
error: function (jqXHR, textStatus, err) {
// jqXHR: jQuery增强的xhr
// textStatus: 请求完成状态
// err: 底层通过throw抛出的异常对象,值与错误类型有关
console.log(arguments);
},
//=================== complete============
complete: function (jqXHR, textStatus) {
// jqXHR: jQuery增强的xhr
// textStatus: 请求完成状态 success | error
console.log('statusCode: %d, statusText: %s', jqXHR.status, jqXHR.statusText);
console.log('textStatus: %s', textStatus);
},
//=================== statusCode============
statusCode: {
'403': function (jqXHR, textStatus, err) {
console.log(arguments); //注意:后端模拟errror方式:HttpResponse.status_code=500
},
'400': function () {
}
}
})
})
</script>
</body>
</html>
import json,time
def index(request):
return render(request,"index.html")
def handle_Ajax(request):
username=request.POST.get("username")
password=request.POST.get("password")
print(username,password)
time.sleep(10)
return HttpResponse(json.dumps("Error Data!"))
二、$.ajax参数
请求参数:
######################------------data---------################
data: 当前ajax请求要携带的数据,是一个json的object对象,ajax方法就会默认地把它编码成某种格式
(urlencoded:?a=1&b=2)发送给服务端;此外,ajax默认以get方式发送请求。
function testData() {
$.ajax("/test",{ //此时的data是一个json形式的对象
data:{
a:1,
b:2
}
}); //?a=1&b=2
######################------------processData---------################
processData:声明当前的data数据是否进行转码或预处理,默认为true,即预处理;if为false,
那么对data:{a:1,b:2}会调用json对象的toString()方法,即{a:1,b:2}.toString()
,最后得到一个[object,Object]形式的结果。
######################------------contentType---------################
contentType:默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。
用来指明当前请求的数据编码格式;urlencoded:?a=1&b=2;如果想以其他方式提交数据,
比如contentType:"application/json",即向服务器发送一个json字符串:
$.ajax("/ajax_get",{
data:JSON.stringify({
a:22,
b:33
}),
contentType:"application/json",
type:"POST",
}); //{a: 22, b: 33}
注意:contentType:"application/json"一旦设定,data必须是json字符串,不能是json对象
views.py: json.loads(request.body.decode("utf8"))
######################------------traditional---------################
traditional:一般是我们的data数据有数组时会用到 :data:{a:22,b:33,c:["x","y"]},
traditional为false会对数据进行深层次迭代;
响应参数:
dataType: 预期服务器返回的数据类型,服务器端返回的数据会根据这个值解析后,传递给回调函数。
默认不需要显性指定这个属性,ajax会根据服务器返回的content Type来进行转换;
比如我们的服务器响应的content Type为json格式,这时ajax方法就会对响应的内容
进行一个json格式的转换,if转换成功,我们在success的回调函数里就会得到一个json格式
的对象;转换失败就会触发error这个回调函数。如果我们明确地指定目标类型,就可以使用
data Type。
dataType的可用值:html|xml|json|text|script
见下dataType实例
from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here. import json def login(request): return render(request,'Ajax.html') def ajax_get(request): l=['alex','little alex']
dic={"name":"alex","pwd":123} #return HttpResponse(l) #元素直接转成字符串alexlittle alex
#return HttpResponse(dic) #字典的键直接转成字符串namepwd
return HttpResponse(json.dumps(l))
return HttpResponse(json.dumps(dic))# 传到前端的是json字符串,要想使用,需要JSON.parse(data) //---------------------------------------------------
function testData() { $.ajax('ajax_get', {
success: function (data) {
console.log(data);
console.log(typeof(data));
//console.log(data.name);
//JSON.parse(data);
//console.log(data.name);
},
//dataType:"json",
}
)} 注解:Response Headers的content Type为text/html,所以返回的是String;但如果我们想要一个json对象
设定dataType:"json"即可,相当于告诉ajax方法把服务器返回的数据转成json对象发送到前端.结果为object
当然,
return HttpResponse(json.dumps(a),content_type="application/json") 这样就不需要设定dataType:"json"了。
content_type="application/json"和content_type="json"是一样的!
三、csrf跨站请求伪造
$.ajaxSetup({data: {csrfmiddlewaretoken:'{{ csrf_token }}'},});
<form>{% csrf_token %}</form><br><br><br>$.ajax({<br>...<br>data:{"csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val();}<br>})
<scriptsrc="{% static 'js/jquery.cookie.js' %}"></script>
$.ajax({headers:{"X-CSRFToken":$.cookie('csrftoken')},})
https://www.cnblogs.com/yuanchenqi/articles/7638956.html
四、示例
要掌握的 //js: 字符串 数组 object{}
编码方式:
url-encode form-data application/json
form / ajax
1.默认: Content-Type: application/x-www-form-urlencoded,
请求体中:
user=yuan&pwd=123
request.POST:
post: <QueryDict: {'user': ['yuan'], 'pwd': ['123']}>
2.上传文件:enctype="multipart/form-data"
formdate = new FormData();
请求体中:
------WebKitFormBoundaryFTMqfCmRXmFBlfK4
Content-Disposition: form-data; name="user"
yuan
------WebKitFormBoundaryFTMqfCmRXmFBlfK4
Content-Disposition: form-data; name="pwd"
123
------WebKitFormBoundaryFTMqfCmRXmFBlfK4--
3.contentType:'application/json',
请求体中:
{"a":1,"b":2}
接收数据:
request.POST,request.GET 收不到数据!!
request.body,才能收到!!
dic = json.loads(request.body.decode('utf-8'))
为什么?
request.body 源数据都在这里
body: b'{"a":1,"b":2}'
django: wsgi 只对 url-encode 转,因此:request.POST 才能拿到数据!
对于json,wsgi不转,需要我们从body中拿数据。
参数:
<script src="/static/js/jquery.cookie.js"></script> headers:{"X-CSRFToken":$.cookie('csrftoken')},
contentType:'application/json',
dataType:'json', # 拿到数据后,json解析数据,若没有,就是str success:function (data) {}
error:function (data) {}
finally:function (data) {}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <form action="" method="post">
{% csrf_token %}
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit">
</form> <hr> <button class="btn">click</button> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="/static/js/jquery.cookie.js"></script>
<script type="text/javascript"> $('.btn').click(function () {
$.ajax({
headers:{"X-CSRFToken":$.cookie('csrftoken')},
url:'/test/',
type:'POST',
contentType:'application/json',
data:JSON.stringify({a:1,b:2,'csrfmiddlewaretoken':$("[name='csrfmiddlewaretoken']").val()}),
dataType:'json',
success:function (data) { // json 字符串 。。。
console.log(data);
console.log(typeof data)
},
error:function (data) {
console.log('error',data)
},
finally:function (data) {
console.log('finally',data)
} }) }); </script> </body>
</html>
def test(request):
if request.method == 'POST':
print("post:",request.POST)
print("get:",request.GET)
print("files:",request.FILES)
print("body:",request.body) import json
dic = json.loads(request.body.decode('utf-8'))
print(dic['a'])
print(dic) # return HttpResponse('OK') info = {'name':'alex'}
return HttpResponse(json.dumps(info)) # return HttpResponse("{'name':'alex'}") return render(request,'test.html')
Django - Ajax - 参数的更多相关文章
- ajax参数补充
ajax参数补充 contentType 当我们使用form表单提交数据时,有一个enctype属性,默认情况下不写 此时我们提交数据时,会默认将数据以application/x-www-form-u ...
- django AJAX 的应用
目录 AJAX 的使用 AJAX简介 AJAX常见应用情景 AJAX的优缺点 jQuery实现的AJAX JS实现AJAX AJAX请求如何设置csrf_token Form表单上传文件 AJAX上传 ...
- Django——Ajax相关
Ajax简介 AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进行异步交互,传输的数 ...
- Django ajax MYSQL Highcharts<1>
Another small project with django/Ajax/Mysql/Highcharts. 看下效果图 - delivery dashboard .嘿嘿 是不是还蛮好看的. 废 ...
- JQuery中的AJAX参数详细介绍
Jquery中AJAX参数详细介绍 参数名 类型 描述 url String (默认: 当前页地址) 发送请求的地址. type String (默认: "GET") 请求方 ...
- 转载 Jquery中AJAX参数详细介绍
Jquery中AJAX参数详细列表: 参数名 类型 描述 url String (默认: 当前页地址) 发送请求的地址. type String (默认: "GET") 请求方式 ...
- django ajax练习
这几天遇到了django ajax请求出错的问题,总结一下 前端js:我这里创建的是一个字典格式的数据,前端js收到字典之后也是要用字典的形式去解包后台传送过来的数据,比如我下面的写法:data['s ...
- jquery $.ajax({});参数详解
用到过的: type:请求方式,默认 GET: url:请求路径: data:请求参数,类型是String:JSON.stringify({"name":tom,"age ...
- ajax参数
$.ajax({ type: "GET", url: "Login.ashx", dataType: "text", cache: fals ...
随机推荐
- 关于VS2012连接MySql数据库时无法选择数据源
您的C#开发工具是用VS2012吗? No! return; 您的数据库用的是MySql吗? No! return; 您新建ADO.NET数据实体模型的时候选择数据源的时候没 ...
- 同一种类型的两个对象赋值,用反射。再也不用点属性了。。。。(适用于ef)
/// <summary> /// 给对象赋值的方法(不赋地址)(同一个类型),含过滤 /// </summary> /// <typeparam name=" ...
- php将汉字转换为拼音和得到词语首字母(四)
<?php function getfirstchar($s0){ $firstchar_ord=ord(strtoupper($s0{0})); if (($firstchar_ord> ...
- XP 终端服务组件 ,SP3 多用户补丁(替换)文件
如附件 termsrv.dll 5.1.2600.5512 目前存在一个问题:每个用户只能使用一个会话.不能像2003+那样,一个用户使用多个会话. 待查找解决方案中............... ...
- HEVC 有损优化一
前期通过X86汇编和C的优化,HEVC 编码有了大幅的提升,目前320x240可以到4~5 fps 了.从现在开始无损优化先放放(还有很大的优化空间),开始做有损优化.做有损优化,我们设定的前提是ps ...
- 【转】VS2008快速将代码中字符串改为_T(“”)风格的方法
用VC在修改一些老程序的时候,经常面临“UNICODE化”的工作.就是将一些传统C语言风格的字符串,如“string”,改为既能够通过多字节编码工程编译,又能通过UNICODE工程编译的代码,即形如_ ...
- mysql数据库中,查看当前支持的字符集有哪些?字符集默认的collation的名字?
需求描述: mysql数据库支持很多字符集,那么如何查看当前的mysql版本中支持的或者说可用的字符集有什么呢? 操作过程: 1.使用show character set的方式获取当前版本中支持的字符 ...
- mysql中" ' "和 " ` "的区别
http://blog.csdn.net/yang3290325/article/details/3349907
- NUC131演示如何通过PWM触发ADC。
今天我来讲讲PWM触发ADC的例程 /**************************************************************************** * @f ...
- 《C++ Primer Plus》10.3 类的构造函数和析构函数 学习笔记
10.3.1 声明和定义构造函数构造函数原型:// constructor prototype with some default argumentsStock(const string &c ...