0
我試圖通過jQuery POST命令傳遞表單數據(Avatar & User ID),但它不會上傳文件。有人可以請我指出我的方向是正確的嗎?這裏是形式和腳本:PHP Image上傳通過JQUERY
<form id="avatar">
<script>
$(document).ready(function()
{
var ok = true;
$('#avatarButton').click(function()
{
var id=$("#id").val();
var avatar = $("#avatar").val();
if(ok == true)
{
$('.avatarValidation').html("Uploading Avatar").removeClass("error").addClass("success");
jQuery.post("php/<?php echo $usertype; ?>/avatar.php", {
id:id,
avatar:avatar
}, function(data, textStatus){
if(data == 1){
$('.avatarValidation').html("Profile Updated").removeClass("error").addClass("success");
}
else if(data == 2){
$('.avatarValidation').html("Error").removeClass("success").addClass("error");
}
});
}
else
{
$('.avatarValidation').html("No").removeClass("success").addClass("error");
}
return false;
});
});
</script>
<table>
<tr>
<td class="textColumn profileColumn">Add Avatar:</td>
<td class="profileInput inputColumn"><input type="file" id="avatar" name="avatar" value="<?php echo $yourname; ?>"/></td>
</tr>
<tr>
<td colspan="2"><input type="hidden" name="id" id="id" value="<?php echo $yourid; ?>"></td>
</tr>
<tr class="buttonSpacer"></tr>
<tr>
<td colspan="2">
<input type="submit" class="submitButton" id="avatarButton" value="Upload Avatar" />
<span class="submitValidation avatarValidation"></span>
</td>
</tr>
</table>
</form>
,這裏是到表單數據傳遞給PHP:
<?php
$id= mysqli_real_escape_string($con, $_REQUEST["id"]);
$avatar= mysqli_real_escape_string($con, $_REQUEST["avatar"]);
if ($_FILES['$avatar']['error'] > 0) {
echo "2"; //Echo Error
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['$avatar']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newName = time() . '_' . $_FILES['$avatar']['name'];
$destination = 'avatar/' . $newName;
if (move_uploaded_file($_FILES['$avatar']['tmp_name'], $destination)) {
echo "1"; //Echo Success
}
} else {
echo "2"; //Echo Error
}
}
?>
它需要多一點使用jQuery AJAX方法上載,你必須建立一個FORMDATA對象和傳遞來代替。此外,它不會在IE <10中工作,所以在oldie中,您必須回退到正常的表單文章。 – 2013-05-13 19:03:03
謝謝@KevinB - 我會看看這個 - 剛剛看到關於使用IFrame的一些東西,以便可以採用這種方式 - 再次感謝 – user2379000 2013-05-13 19:08:50
您可以使用iframe技術 – 2013-05-13 19:19:10