如何接收&使用XMLHttpRequest发送到php的进程数据?

时间:2015-09-20 20:54:53

标签: javascript php xmlhttprequest xmlhttprequest-level2

我正在处理mp3文件的上传表格,我碰壁了:/。你能帮忙吗?

这是我的HTML:

<form id="file-form" method="POST">
<input class="profileMenu" id="mp3file" name="mp3file" type="file" multiple/>    
</form>
<div onclick="test()" class="col-md-1 profileMenu" id="uploadButton">Upload</div> 

这是我的JavaScript:

function test() {
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('mp3file');
var uploadButton = document.getElementById('uploadButton');

uploadButton.innerHTML = 'Uploading...';

var files = fileSelect.files;
var formData = new FormData();

for (var i = 0; i < files.length; i++) {
    var file = files[i];
    formData.append('mp3file', file, file.name);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'php/commercial/upload.php', true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            uploadButton.innerHTML = 'Upload';
        }
        else {
            alert('An error occurred!');
        }
    };
    xhr.send(formData);
}    
}

最后我的PHP:

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['filename']['name']); 

if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['filename']['name']). " has been uploaded"; 
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

我正在尝试将mp3文件上传到我的服务器并在文件夹中对它们进行排序,表单验证正常,请求不会返回任何错误,而且似乎我的php代码没有做它应该是什么,我知道我可以使用提交按钮而不使用JavaScript,但我需要这样做。所以,如果你们有任何想法我会非常感激。

0 个答案:

没有答案