s14_05_Ajax
- Ajax
- 参考博客:
http://www.cnblogs.com/wupeiqi/articles/5703697.html
- 原生ajax(XMLHttpRequest)
- jQuery
- 伪Ajax操作(iframe)
- 使用时机:
如果发送的是【普通数据】
1. jQuery
2. XMLHttpRequest
3. iframe
- 文件上传
- Form提交
- Ajax上传文件(xhr/jQuery)
- 使用时机:
如果发送的是【文件】
1. iframe
2. jQuery(FormData)
3. XMLHttpRequest(FormData)
- ajax 和 文件上传 代码
# urls.py
url(r'^ajax/$', views.ajax),
url(r'^ajax_json/$', views.ajax_json),
url(r'^upload/$', views.upload),
url(r'^upload_file/$', views.upload_file),
# view.py
def ajax(request):
return render(request,'ajax.html')
def ajax_json(request):
print(request.POST)
ret ={'status':True,'data':request.POST.get('username')}
import json
# return HttpResponse(json.dumps(ret),status=404,reason='Not Found')
return HttpResponse(json.dumps(ret))
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
fafafa = request.FILES.get('fafafa')
print(username,fafafa)
import os
img_path =os.path.join('static/imgs/',fafafa.name)
with open(img_path,'wb') as f:
for item in fafafa.chunks():
f.write(item)
ret ={'status':True,'data':img_path}
import json
return HttpResponse(json.dumps(ret))
# ajax.html
<body>
<input type="text">
<input type="button" value="Ajax1" onclick="Ajax1();">
<!--
ifram 演示
<input type="text" id="url">
<input type="button"value="发送iframe" onclick="iframeRequest();">
<iframe id= 'ifm' src="http://www.baidu.com" frameborder="0"></iframe>
-->
<form action="/ajax_json/"method="POST" target="ifm1">
<iframe id="ifm1" name="ifm1" ></iframe>
<input type="text"name="username">
<input type="text"name="email">
<input type="submit" value="Form提交" onclick="submitForm();">
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script>
//兼容性设置
function getXHR(){
var xhr = null;
if (XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
return xhr;
}
//原生 ajax get请求
/*
function Ajax1(){
var xhr = new XMLHttpRequest();
xhr.open('GET','/ajax_json/',true);
xhr.onreadystatechange = function () {
if (xhr.readyState ==4){
console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.setRequestHeader('k1','v1');
xhr.send('name=root;pwd=123');
};
*/
//原生 ajax post请求
function Ajax1(){
//未包含csrf_tonken
// POST发送需要加请求头
var xhr = getXHR();
//var xhr = new XMLHttpRequest();
xhr.open('POST','/ajax_json/',true);
xhr.onreadystatechange = function () {
if (xhr.readyState ==4){
console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.setRequestHeader('k1','v1');//csrf_token
xhr.setRequestHeader('Content_Type','application/x-www-form-urlencoded');
xhr.send('name=root;pwd=123');
}
/*
// jquery ajax,参数a1,a2 有一个同xhr
$.ajax({
success: function (arg, a1, a2) { }
})
*/
/*
iframe 演示
function iframeRequest(){
var url = $('#url').val();
$('#ifm').attr('src',url);
}
*/
function submitForm(){
$('#ifm1').load(function () {
var text = $('#ifm1').contents().find('body').text();
// console.log(text);
var obj =JSON.parse(text);
})
}
</script>
</body>
</html>
# upload.html
<head>
<meta charset="UTF-8">
<title></title>
<style>
.upload{
display: inline-block;
padding: 8px;
background-color:cornflowerblue;
position: absolute;
top:0;
bottom: 0;
right:0;
left:0;
z-index: 90;
}
.file{
width: 100px;height: 50px;
opacity: 0;
position: absolute;
top:0;
bottom: 0;
right:0;
left:0;
z-index: 100;
}
</style>
</head>
<body>
<div style="position: relative; width: 100px;height: 50px;">
<input class="file" type="file" id="fafafa" name="afafaf">
<a class="upload" >上传</a>
</div>
<input type="submit" value="提交XHR" onclick="xhrSubmit();">
<input type="submit" value="提交jquery" onclick="jqSubmit();">
<hr>
<form id="form1" action="/upload_file/"method="POST" enctype="multipart/form-data" target="ifm1">
<iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
<input type="file"name="fafafa" onchange="changeUpload();">
{# <input type="submit" value="Form提交" onclick="ifmSubmit();">#}
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function changeUpload(){
$('#ifm1').load(function () {
var text = $('#ifm1').contents().find('body').text();
var obj =JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src='/'+ obj.data;
$('#preview').append(imgTag);
});
$("#form1").submit();
}
function jqSubmit(){
var file_obj = document.getElementById('fafafa').files[0];
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('username','root');
fd.append('fafafa',file_obj);
$.ajax({
url:'/upload_file/',
type:'POST',
data:fd,
processData:false,
contentType:false,
success: function (arg, a1, a2) {
console.log(arg);
console.log(a1);
console.log(a2);
}
})
}
function xhrSubmit(){
var file_obj = document.getElementById('fafafa').files[0];
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('username','root');
fd.append('fafafa',file_obj);
xhr.open('POST','/upload_file/',true);
xhr.onreadystatechange = function () {
if (xhr.readyState ==4){
console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.send(fd);
}
function ifmSubmit(){
$('#ifm1').load(function () {
var text = $('#ifm1').contents().find('body').text();
{# console.log(text);#}
var obj =JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src='/'+ obj.data;
$('#preview').append(imgTag)
})
}
</script>
</body>
- Ajax2
$.ajax({
url: '/host/',
type: "POST",
data: {'k': 'v', 'list': [1,2,3,4], 'k3': JSON.stringfy({'k1': 'v'}))} --> $('form对象').serilize(),
dataType: 'JSON',
traditional: true,
success: function(data){
// data是服务器端返回的字符串
var obj = JSON.parse(data);
location.reload() # 刷新
location.href = "某个地址" # 跳转
}
})
$.get(url='xx',data={})
$.getJson
$.post
# 建议:永远让服务器端返回一个字典
# return HttpResponse(json.dumps(字典))