[英]Uploading file to php through ajax
我的表單使用javascript警報與用戶進行交流,因為這是我工作的公司中的首選方法(而不是與php處理程序文件進行不斷重定向)。
因此,我將所有表單數據通過jquery中的一些簡單驗證傳遞,並通過ajax發送到php處理程序。 這是我的基本做法...
var first_name = $(sender + ' #first_name');
var email = $(sender + ' #email');
var tel = $(sender + ' #telephone');
var comments = $(sender + ' #comments');
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: { first_name: first_name.val(),
email: email.val(),
telephone: tel.val(),
comments: comments.val(),
success: function clearFields() {
first_name.val('');
email.val('');
tel.val('');
comments.val('');
alert('Thank you. We will contact you as soon as possible.');
}
}
});
將文件輸入字段添加到如下所示的一種表單中后,我在上傳時遇到了麻煩。 雖然電子郵件正確發送,但我認為ajax不會發送任何可用數據以上傳到php文件
<input type="file" name="upload" id="upload" />
<script>
var upload = $("#upload");
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: { first_name: first_name.val(),
email: email.val(),
telephone: tel.val(),
upload: upload.val(),
comments: comments.val(),
success: function clearFields() {
first_name.val('');
email.val('');
tel.val('');
upload.val('');
comments.val('');
alert('Thank you. We will contact you as soon as possible.');
}
}
});
</script>
我發現了一些這個選項,但所有的人我看過像這樣似乎“的hackish”給我。
有沒有更簡單的方法可以做到這一點?
Ajax不支持file
上傳操作。 但是,有許多插件可以利用iframe異步上傳文件。 您可以在此處閱讀有關此技術的更多信息。
很少有支持表單上傳的jQuery插件是
1. jQuery表單
2. jQuery文件上傳
在許多Q&A站點中,有很多與此相關的問題答案,例如這個 。
這里討論使用html 5的另一個解決方案,該解決方案使用FormData。
您必須通過IFrame進行此操作
因此,您創建了一個隱藏的iframe
<iframe id="upload_target" name="upload_target" style="display: none;" src="#"></iframe>
<!-- note the src="#" -->
然后,創建一個帶有一些按鈕以及您希望擁有的所有字段的表單
<form action="path/to/uploadscript.php" method="POST" enctype="multipart/form-data" target="upload_target">
<!--target will tell the browser to run it in the iFrame with name="upload_target" -->
然后在uploadscript.php中,您可以使用所有表單值,就像它們是常規的$ _POST值一樣:
<?php upload_file($_FILES['file'], $_POST['name'], $_POST['whatever']); ?>
這幾乎與使用AJAX一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.