我正在尝试使用jQuery提交服务器端处理的完整表单。该表格包含各种字段,包括文件上传选项。我试图使用FormData来做到这一点,因为我不关心目前不支持它的浏览器。jQuery FormData POST - 用于文件上传
我有以下的(简化)jQuery代码:
$("#create_event_form").submit(function(event) {
event.preventDefault();
var formData = new FormData($(this));
$.post(
"create_entity.php",
{ formData: formData },
function(data) {
var response = jQuery.parseJSON(data);
if(response.code == "success") {
alert("Success!");
} else if(response.code == "failure") {
alert(response.err);
}
}
);
});
我的服务器端如下所示:
<?php
require_once('includes/database.php');
$dbh = db_connect();
$response = array();
if($_SERVER['REQUEST_METHOD'] == "POST") {
// do some other stuff...
// upload entity picture and update database
$url = $_FILES['entity_pic']['name'];
if($url != "") {
if($type == "user") {
$pic_loc = "images/profiles/";
} else if($type == "chapter") {
$pic_loc = "images/chapters/";
} else if($type == "group") {
$pic_loc = "images/groups/";
} else if($type == "event") {
$pic_loc = "images/events/";
}
// upload the picture if it's not already uploaded
if(!file_exists($pic_loc . $_FILES['entity_pic']['name'])) {
move_uploaded_file($_FILES['entity_pic']['tmp_name'], $pic_loc . $url);
}
$image_query = "INSERT INTO image (entity_id, url, type) VALUES (:entity_id, :url, :type);";
$image_query_stmt = $dbh->prepare($image_query);
$image_query_stmt->bindParam(":entity_id", $entity_id);
$image_query_stmt->bindParam(":url", $url);
$image_query_stmt->bindValue(":type", $type);
if(!$image_query_stmt->execute()) {
die(print_r($image_query_stmt->errorInfo()));
}
}
echo json_encode($response);
}
>
和一些相关的HTML:
<form id="create_event_form" action="create_entity.php" method="POST" enctype='multipart/form-data'>
<input type="file" name="entity_pic" value="Insert Photo" />
<!-- other inputs -->
</form>
现在我得到一个非法的调用错误,可能是我的FormData对象的初始化。我一直在寻找关于如何使用jQuery来做这个事情的例子,并且我会空着。另外,我想澄清一下,我的服务器端代码将起作用。当我将formData作为“formData”传递给我的PHP脚本时,如何访问其中的字段?它会是“$ _POST ['formData'] ['field_name']”或只是$ _POST ['field_name']或其他完全?
感谢您的任何帮助。
类似[这](http://stackoverflow.com/questions/6974684/how-发送formdata-objects-with-ajax-requests-in-jquery)也许这个问题呢? –
唯一的问题是我想提交的表单中有很多其他值。我是否必须为每个人添加附录声明?我曾希望我可以使用表单引用来初始化FormData对象... – jrubins
此外,我需要帮助了解如何在我的服务器端代码中处理提交的FormData对象 – jrubins