通过ajax上传文件到php [英] Uploading file to php through ajax
问题描述
我的表单使用javascript警报与用户进行通信,因为这是我工作的公司中的首选方法(而不是不断重定向到php处理程序文件和从php处理程序文件重定向)。
正因为如此,我通过jQuery中的一些简单验证来传递所有表单数据,并通过ajax将其发送到php处理程序。这里有一个基本的看看我是怎么做到的...
My form uses javascript alerts to communicate with the user as this is the preferred method in the company I work for (as opposed to constant redirects to and from the php handler file).
Because of this, I pass all my form data through some simple validation in jquery and send it on to the php handler via ajax. Here's a basic look at how I'm doing it...
将文件输入字段添加到如下所示的一个表单中, 。虽然电子邮件发送正确,我不认为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.');
}
}
});
Having added an file input field to one such form as follows, I'm having trouble with the upload. While the email sends correctly, I don't think the ajax is sending any usable data for the upload on to the php file
我发现了很多选项,但是我看过的所有选项<对我来说这似乎是hackish。
<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>
有没有更简单的方法来做到这一点?
Is there a simpler way to do this?
推荐答案
通过IFrame
所以你创建一个隐藏的iframe b
$ b
So you create a hidden iframe
<iframe id="upload_target" name="upload_target" style="display: none;" src="#"></iframe>
<!-- note the src="#" -->
然后,您创建一个表单,其中包含一些按钮以及所有您想要的字段
Then you create a form with some button and all fields you wish to have
<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值一样使用所有表单值: / p>
then in uploadscript.php you can use all form values as if they are regular $_POST values:
<?php upload_file($_FILES['file'], $_POST['name'], $_POST['whatever']); ?>
这与使用AJAX几乎一样。
This almost feels the same as using AJAX.
这篇关于通过ajax上传文件到php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!