事呢,就是這麼個事。iphone如果你發送的formdata數據中文件有空,在數據表現爲file.size==0;此時試用iphone是會發送失敗的;無奈只好做個判斷了;
1. 問題分析
/*
* 爲了使用ajax上傳圖片,使用了FormData的解決方案,代碼如下。
* 實際請求時:發現在iphone中在input[type=file]裏面有內容的時候是可以成功請求的;
* 但是當input[type=file]裏面內容爲空的時候卻不能成功發送請求
* (備註:Android機沒遇到此情況,由此斷定,是瀏覽器內核不同導致的)。
*/
var regData = {url:'...', isCommit:false, data:''};
$('#commitBtn').click(function(){
if (regData.isCommit) {
return false;
}
regData.isCommit = true;
regData.data = new FormData($('#regForm')[0]);
$.ajax({
type: 'POST',
url: regData.url,
data: regData.data,
dataType: 'json',
contentType: false,
processData: false,
success: function (res) {
console.log(res);
regData.isCommit = false;
},
error: function () {
regData.isCommit = false;
}
});
});
2. 解決方案:
/**
* 因爲時間比較緊急,也沒尋找更好的解決方案。如果有大神有更好的解決方案的話,希望留言共享。
* 判斷file是否爲空,發不同的請求數據
*/
if ($('input[name=file]').prop('files').length == 0) {
//input[type=file]爲空
regData.data = $('#regForm').serialize();
$.ajax({
type: 'POST',
url: regData.url,
data: regData.data,
dataType: 'json',
success: function (res) {
console.log(res);
regData.isCommit = false;
},
error: function () {
regData.isCommit = false;
}
});
} else {
//input[type=file]不爲空, 執行 new FormData
}