我的$ .ajax请求在iOS 11.3上停止正常工作
这段代码过去常常工作得很好。
This code used to work just fine and fast for years.
鉴于$ .ajax没有收到任何文件数据,从更新到iOS 11.3开始,这个$ .ajax似乎工作得非常慢,最多只需20秒就能提交一个简单的在iOS浏览器上测试时,纯文本格式。
Given that $.ajax does not receive any file data, as of update to iOS 11.3 this $.ajax seems to work very slowly up to 20 seconds to submit a simple text-only form when tested on iOS browser.
但是如果文件元素传递文件数据,$ .ajax在两种情况下都能正常工作,并且和预期一样快。
But if the file element passes file data, the $.ajax works just fine in both cases and just as fast as expected.
HTML ---
<form enctype="multipart/form-data" id="chatform" method="post">
<input type="file" name="pic" id="pic" class="hidden" />
<textarea name="chattextarea" id="chattextarea" rows="3" cols="10"></textarea>
<input type="button" value="Send" onclick="sendMessage();" />
</form>
JavaScript ---
function sendMessage() {
var formData = new FormData($("#chatform")[0]);
$.ajax({
url: 'send.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
/* some success message */
}
});
}
这是iOS 11.3的错误吗?
Is this an iOS 11.3 bug?
-----编辑-----
----- EDIT -----
是的确它不仅是iOS 11.3的bug,而且还是Safari 11.1的bug。
到目前为止,我测试了这些环境并复制了这个错误:
Yes indeed it is not only iOS 11.3 bug, but also a Safari 11.1 bug. So far I tested these environments and replicated the bug:
- Mac OS,Safari
- iOS,Safari
- iOS,Chrome
- iOS,WKWebView(混合应用)
- Mac OS, Safari
- iOS, Safari
- iOS, Chrome
- iOS, WKWebView (hybrid app)
我写了一个简单的解决方法,请检查我的答案,如果你有更清洁的解决方案,请告诉我。
I wrote a simple workaround, please check my answer and let me know if you have a cleaner solution.
此功能适用于iOS 11.3,iOS 10.2和Windows Chrome 65.0.3325.181。
有人可以帮助在其他浏览器上测试吗?
This function works on iOS 11.3, iOS 10.2 and windows Chrome 65.0.3325.181. Can someone help to test on other browsers?
function formDataFileFix(formData) {
try {
if (formData.keys) {
var formKeysToBeRemoved = [];
for (var key of formData.keys()) {
var fileName = null || formData.get(key)['name'];
var fileSize = null || formData.get(key)['size'];
if (fileName != null && fileSize != null && fileName == '' && fileSize == 0) {
formKeysToBeRemoved.push(key);
}
}
for (var i = 0; i < formKeysToBeRemoved.length; i++) {
formData.delete(formKeysToBeRemoved[i]);
}
}
}
catch(err) {
console.log(err.message);
}
}
var formData = new FormData($(formID)[0]);
formDataFileFix(formData);