无法在php中获取ajax发送数据

时间:2018-02-02 11:10:12

标签: javascript php ajax

我是网络开发的新手,我正在使用Ajax在PHP上进行图片上传。我在接收PHP中的ajax发送数据时遇到问题。我花了几个小时找到解决方案,但我不能。

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <h2 id="msg"></h2>
    <input type="file" name="img" id="img">
    <button onclick="uploadImg();" type="button">Upload</button>
</body>
</html>

的Javascript

function uploadImg() {

        var img = document.getElementById('img').value;
        var data = "data=img";

        var xmlhttp = new XMLHttpRequest();

        xmlhttp.open("POST", "upload.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("msg").innerHTML = this.responseText;
            }
        };

        xmlhttp.send(data);
    }

PHP

<?php
    $file = $_FILES['data']['tmp_name'];
    $uploadTo = "uploads/"; 
    $name = $_FILES['data']['name'];

    if( move_uploaded_file($file, $uploadTo.$name) ) {
        echo "SUCCESS";
    } else {
        echo "ERROR";
    }
?>

0 个答案:

没有答案