這篇文章主要介紹了jQuery 利用$.ajax 時(shí)獲取原生XMLHttpRequest 對(duì)象的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
關(guān)鍵代碼如下所示:
<script>
$('.screenshot_input').change(function (){
//獲取file對(duì)象 即相當(dāng)于可以直接post的$_FILES數(shù)據(jù)
var domFile = $(this)[0].files[0]
var domForm = $('#testForm')[0]
//將form對(duì)象直接作為參數(shù) new FormData對(duì)象
var formData = new FormData(domForm);
//追加file 對(duì)象
formData.append('file',domFile);
$.ajax({
url:'{{ path( 'acme_admin_app_dealAppScreenShot') }}',
type: "POST",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
xhr: function(){ //這是關(guān)鍵 獲取原生的xhr對(duì)象 做以前做的所有事情
var xhr = jQuery.ajaxSettings.xhr();
xhr.upload.onload = function (){
alert('finish downloading')
}
xhr.upload.onprogress = function (ev) {
if(ev.lengthComputable) {
var percent = 100 * ev.loaded/ev.total;
console.log(percent,ev)
}
}
return xhr;
},
success:function(data){
alert(data)
}
})
})
</script>
Array
(
[name] => cooff
[email] => qq.comaa
)
Array
(
[file] => Array
(
[name] => yunce2.0測(cè)試.apk
[type] => application/vnd.android.package-archive
[tmp_name] => /tmp/php4Jxt0c
[error] => 0
[size] => 6476627
)
)
一次過(guò)把form表單 和 file 對(duì)象發(fā)送到PHP后端controller 處理起來(lái)非常方便。
以上所述是小編給大家介紹的jQuery 利用$.ajax 時(shí)獲取原生XMLHttpRequest 對(duì)象,希望對(duì)大家有所幫助