我正在尝试使用form data
对象将值发送到ajax
调用并使用php
文件获取值,但是显然form data
值是错误的。>
这就是我所做的。这是我的html
<thead>
<tr class="text-center">
<th class="text-center">Subject</th>
<th class="text-center">Upload</th>
</tr>
</thead>
<tbody>
<tr>
<td>Physics 1</td>
<td>
<label class="btn btn-default">
<input type="file" onchange="changeColor(this, 'p1')" accept=".doc,.docx,.pdf" name="p1" id="p1" hidden>
</label>
<button type="button" onclick="uploadFileIAL('ial', 'Physics 1', 'p1')" class="btn btn-success" aria-expanded="false">Upload</button>
<button type="button" onclick="removeFile('ial', 'Physics 1', 'p1')" id="p1" class="btn btn-danger" aria-expanded="false">X</button>
</td>
</tr>
<tr>
<td>Physics 2</td>
<td>
<label class="btn btn-default">
<input type="file" onchange="changeColor(this, 'p2')" accept=".doc,.docx,.pdf" name="p2" id="p2" hidden>
</label>
<button type="button" onclick="uploadFileIAL('ial', 'Physics 2', 'p2')" class="btn btn-success" aria-expanded="false">Upload</button>
<button type="button" onclick="removeFile('ial', 'Physics 1', 'p2')" id="p2" class="btn btn-danger" aria-expanded="false">X</button>
</td>
</tr>
<tr>
<td>Physics 3</td>
<td>
<label class="btn btn-default">
<input type="file" onchange="changeColor(this, 'p3')" accept=".doc,.docx,.pdf" name="p3" id="p3" hidden>
</label>
<button type="button" onclick="uploadFileIAL('ial', 'Physics 3', 'p3')" class="btn btn-success" aria-expanded="false">Upload</button>
<button type="button" onclick="removeFile('ial', 'Physics 3', 'p3')" id="p3" class="btn btn-danger" aria-expanded="false">X</button>
</td>
</tr>
</tbody>
</table>
这是我的javascript ajax
<script type="text/javascript">
function uploadFileIAL(igcseOrIal, subject, fileid) {
var data = new FormData();
jQuery.each(jQuery('#p1')[0].files, function(i, file) { //this scope is not executing for some reason
alert(i); //this is not printing, since scope is not executing
data.append('file' + i, file);
data.append('subject', subject);
});
$.ajax({
url: 'includes/upload-ial-pastpapers.php',
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: data,
type: 'post',
success: function(data) {
alert(data); //prints "error" from php file
$("#" + fileid).val(null);
// $("button[id='"+fileid+"']").hide();
// $("#" + fileid).css({"backgroundColor": "", "color": ""});
}
});
}
</script>
这是我的php
文件
include_once './connection.php';
if (isset($_FILES['file0'])){ //this scope is not executing, gives undefined 'file0'
echo 'ok';
$file = $_FILES['file0'];
$fileName = $_FILES['file0']['name'];
$fileTempName = $_FILES['file0']['tmp_name'];
$fileSize = $_FILES['file0']['size'];
$fileError = $_FILES['file0']['error'];
$fileType = $_FILES['file0']['type'];
$subject = $_POST['subject'];
echo $subject;
//uploadPhotos($conn, $fileName, $fileError, $fileSize, $fileTempName, $subject);
}else{
echo "error"; //this part is executes and sends to `ajax` to alert();
}
有人可以帮我解决我做错的事情吗?