我试图添加一个“上传图像”功能到我的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