我有一个带有表单的HTML,如下所示:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
和.php这样的脚本:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
问题: 在submitform()函数中,在以下行的脚本标记中:
data = $('*').serialize();
为什么我得到空的结果? 代码有什么问题?
谢谢
答案 0 :(得分:1)
更改此
data = $('*').serialize();
到
data = $('theform').serialize();
并更改此
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
到
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
答案 1 :(得分:0)
尝试如下所述:http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});
答案 2 :(得分:0)
答案 3 :(得分:0)
你无法使用Ajax上传文件,如果你必须以类似AJAX的方式上传文件,你可以使用隐藏的iframe,设置目标属性等于iframe并获取iframe的内容以了解请求是否失败< / p>
这就是我通常为此目的所做的,创建一个隐藏的iframe,它将成为表单的目标,如下所示:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
并且在processResult中,您可以通过以下方式获取iframe的内容:
$(results).html();
这样当iframe被加载时,它会自动触发函数通知请求完成