0
我使用talkerscode.com的代碼來實現文件上傳使用拖放。代碼正在工作。現在我想在同一個ajax文章中添加額外的輸入值。我在下面的html代碼中添加一個名爲「user_id」的輸入標籤。我將這個元素附加到formdata對象中。更改後拖放上傳仍然有效,但PHP代碼抱怨未定義$ _POST [「user_id」]。這是我的代碼。請幫忙!jQuery ajax後使用FormData()追加數據元素後無法找到附加的數據元素
<html>
<!-- code original from talkerscode.com -->
<head>
<link rel="stylesheet" type="text/css" href="upload_style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="wrapper">
<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">
<div id="drop-area">
<h3 class="drop-text">Drag and Drop Images Here</h3>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
$("#drop-area").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop-area").on('dragover', function (e){
e.preventDefault();
});
$("#drop-area").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.preventDefault();
var image = e.originalEvent.dataTransfer.files;
createFormData(image);
});
});
function createFormData(image)
{
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val());
uploadFormData(formImage);
}
function uploadFormData(formData)
{
$.ajax({
url: "upload_image.php",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData: false,
success: function(data){
$('#drop-area').html(data);
}});
}
</script>
----------------PHP code -------------------
<?php
if(is_array($_FILES))
{
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "images/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>">
<p> user_id = <?php echo $_POST["user_id"] ?> </p>
<?php
exit();
}
}
}
?>
-----------------------------------------------
後,我申請的變化PHP不再抱怨未定義$ _ POST [ 「user_ID的」。但沒有返回任何價值。它假設返回1228. – CK8
你可以嘗試'console.log($('#user_id')。val())' – aldrin27
我檢查formImage.append('user_id',$('#user_id ),纈氨酸());通過使用alert(「user_id」+ $('#user_id),val()); – CK8