urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^test/$', views.test, name='test'),
url(r'^ajax_test/', views.ajax_test, name='ajax_test'),
]
```javascript
template-ajax_test.html
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="a1">
<input type="file" id="a2">
<input type="button" value="点击" onclick="ajax1()">
</body>
<script src="/static/jquery.js"></script>
<script type="text/javascript">
function getXHR(){
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function ajax1(){
var a1 = document.getElementById('a1').value; #获取input的值
var fileobj = document.getElementById('a2').files[0];
var fd = new FormData();
fd.append('user', a1);
fd.append('img', fileobj);
//var xhr = new XMLHttpRequest();
var xhr = new getXHR();
xhr.open('POST' ,'/ajax_test/', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
************************************************************
//xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
//xhr.send("user=root/pass=123"); #如果send传字符串,必须加上面的请求头, 如果传对象借助FormData,且不用加请求头
***********************************************************
xhr.send(fd);
}
</script>
</html>
views.py
def test(request):
return render(request, 'ajax_test.html')
def ajax_test(request):
res = {'status': True, 'data': 'ok'}
if request.method == 'POST':
print request.POST.get('user')
img = request.FILES.get('img')
import os
file_path = os.path.join('static', img.name) 拼接成 static/xx.jpg
with open(file_path, 'wb') as f:
for i in img.chunks():
f.write(i)
***********************************************************
import json
return HttpResponse(json.dumps(res))
************************************************************
1.原生XMLHttpRequest传送数据,send()发送的是字符串,而且必须使用setRequestHeader设置信息请求头.
2.FormData对象介质传送数据,通过append将(可以看为元组信息)信息传入,然后send(),但send对象为form对象,此种方式不需要设置信息请求头.
3.特别需要注意的一点:如果使用GET方式,需要设置URL,字符串方式.