我試圖添加一個「上傳圖像」功能到我的AjaxChat窗口。上傳到服務器效果很好,但現在我需要能夠返回上傳文件的tmp_name /位置。在我的javascript我有如下(主)代碼(一些設置代碼已經因爲這是不必要的省略 - 上傳的作品如預期):從PHP返回值從PHP調用XMLHttpRequest
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function() {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
我的PHP代碼(「upload.php的」)是如下:
<?php
$valid_file = true;
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
exit("$message");
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
exit("$message");
}
}
//if there is an error...
else {
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
exit("$message");
}
}
?>
我可以告訴我的PHP代碼正在運行,因爲圖像上傳到服務器。但是,我讀,我可以使用下面的代碼生成在PHP中一個JavaScript「警報」彈出:
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
但上面的線似乎並沒有被做任何事情。這是預期的,因爲我使用XMLHttpRequest,而不是直接運行PHP?
最終,我的目標是將上傳文件的名稱傳回給調用PHP的Javascript,以便我可以創建圖像url,將其放入img標記中,並使用ajaxChat.insertText將其發送到聊天窗口()和ajaxChat.sendMessage()。不過,我不確定這是否可以像我運行我的PHP一樣。如何去做這件事?
'echo'只適用於正常的表單提交,而不是AJAX。使用AJAX,腳本的輸出位於'xhr.responseText'中,'xhr.onload'函數可以完成它所希望的功能。 – Barmar