从 XMLHttpRequest 调用的 PHP 返回值到 Javascript [英] Returning value to Javascript from PHP called from XMLHttpRequest

查看:42
本文介绍了从 XMLHttpRequest 调用的 PHP 返回值到 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的 AjaxChat 窗口添加上传图像"功能.上传到服务器效果很好,但现在我需要能够返回已上传文件的 tmp_name/location.在我的 Javascript 中,我有以下(主要)代码(一些设置代码已被省略,因为它是不必要的——上传按预期工作):

I am attempting to add an "Upload Image" feature to my AjaxChat window. The upload to the server works great, but now I need to be able to return the tmp_name/location of the file that was uploaded. In my Javascript I have the following (main) code (some setup code has been omitted because it is unnecessary -- The upload works as expected):

// 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")如下:

My PHP code ("upload.php") is as follows:

<?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警报"弹出窗口:

I can tell my PHP code is being run because the image uploads to the server. However, I read that I could generate a Javascript "alert" popup from within the PHP using the following code:

echo '<script type="text/javascript">alert("PHP 代码到达");</script>';

但是上面那行似乎没有做任何事情.这是预期的,因为我使用的是 XMLHttpRequest,而不是直接运行 PHP?

But the above line does not seem to be doing anything. Is this expected since I'm using an XMLHttpRequest, rather than running the PHP directly?

最终我的目标是将上传文件的名称传回调用 PHP 的 Javascript,以便我可以创建图像 url,将其放入 img 标签中,然后使用 ajaxChat.insertText() 和 ajaxChat.sendMessage().不过,我不确定我运行 PHP 的方式是否可行.怎么做呢?

Ultimately my goal is to pass the name of the uploaded file back to the Javascript that called the PHP so that I can create the image url, put it in img tags, and send it to the chat window using ajaxChat.insertText() and ajaxChat.sendMessage(). I'm not sure if this is possible the way I'm running my PHP, though. How would one go about doing this?

推荐答案

当您使用 XMLHttpRequest 时,服务器脚本的输出在对象的 responseText 中.所以你可以这样做:

When you use XMLHttpRequest, the output of the server script is in the responseText of the object. So you can do:

xhr.onload = function () {
    if (xhr.status === 200) {
        //File(s) uploaded
        uploadButton.innerHTML = xhr.responseText;
    } else {
        alert('An error occurred!');
    }
};

如果你想发回多条信息,比如信息性消息和文件名,你可以使用 JSON 编码一个关联数组,当你解析它时它会变成一个 Javascript 对象.

If you want to send back multiple pieces of information, such as an informative message and the name of the file, you can use JSON to encode an associative array, which will become a Javascript object when you parse it.

这篇关于从 XMLHttpRequest 调用的 PHP 返回值到 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆