我正在尝试将文件上传功能添加到联系表单中,但由于某种原因它无法正常工作。上传脚本本身可以正常工作,但是当我将它添加到联系人代码时,jquery脚本会使其失败。
正如你所知,我绝不是专家。
pontact.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#contact_form').submit(function(e){
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader', form).html('<img src="loader.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
});
</script>
</head>
<body>
<form action="process.php" method="post" id="contact_form">
<div>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
</div>
<div>
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="" tabindex="2" />
</div>
<div>
<label for="message">Message:</label>
<textarea cols="40" rows="8" name="message" id="message"></textarea>
</div>
<div>
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
</div>
<div id="loader">
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
Process.php
$uploaddir = '/var/www/download/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
答案 0 :(得分:0)
即使您拨打form.serialize()
,文件上传也无法通过jQuery运行。
您可以通过黑客实现相同的效果,例如使用iFrame(此处为article}或Uploadify等基于Flash的上传器。
答案 1 :(得分:0)
默认情况下,您无法使用ajax(Why can't I upload files asynchronously?)
上传文件但是有一些技术,包括你可以使用的iframe或flash插件
希望这有帮助