繁体   English   中英

通过Ajax将文件上传到php

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM