ajax之---上传文件
“伪”ajax向后台提交文件
<iframe style="display: none" id="iframe1" name="ifra1"></iframe>
<form id="fm1" action="/ajax1.html" method="POST" enctype="multipart/form-data" target="ifra1">
<input type="text" name="k1" />
<input type="text" name="k2" />
<input type="file" name="k3" />
<a onclick="AjaxSubmit8()">提交</a>
</form>
<script>
function AjaxSubmit8() {
document.getElementById('iframe1').onload = reloadIframe1;
document.getElementById('fm1').submit();
}
function reloadIframe1() {
var content = this.contentWindow.document.body.innerHTML;
var obj = JSON.parse(content);
console.log(obj);
}
</script>
jquery ajax向后台提交文件
<input type="file" id="img" />
<a class="btn" onclick="AjaxSubmit6();">上传</a>
<script>
function AjaxSubmit6() {
//document.getElementById('img')[0]
var data = new FormData();
data.append('k1','v1');
data.append('k2','v2');
data.append('k3',document.getElementById('img').files[0]);
$.ajax({
url: '/ajax1.html',
type: 'POST',
data:data,
success:function (arg) {
console.log(arg)
},
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
})
}
</script>
原生ajax向后台提交文件
<input type="file" id="img" />
<a class="btn" onclick="AjaxSubmit6();">上传</a>
<script>
function AjaxSubmit7() {
var data = new FormData();
data.append('k1','v1');
data.append('k2','v2');
data.append('k3',document.getElementById('img').files[0]);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
// 接收完毕服务器返回的数据
console.log(xhr.responseText);
}
};
xhr.open('POST','/ajax1.html');
xhr.send(data);
}
</script>