【发布时间】:2016-08-11 05:21:47
【问题描述】:
我正在尝试向我的 AjaxChat 窗口添加“上传图像”功能。上传到服务器效果很好,但现在我需要能够返回已上传文件的 tmp_name/位置。在我的 Javascript 中,我有以下(主要)代码(一些设置代码已被省略,因为它是不必要的——上传按预期工作):
// 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函数可以根据需要进行处理。
标签: javascript php xmlhttprequest return-value