php - AJAX/Javascript 上传 PHP 问题

标签 php javascript ajax upload

我一直致力于制作一个通过 ajax 上传图像的表单,并使用 php 进行上传。对于某些背景,我遇到 xhr.readyState 和 .Status 似乎在运行并且 upload.php 似乎在运行的问题(在 safari 中它运行 upload.php 在我看来......我没有使用 ajax/javascript 调试器太多了),但它会运行我的 else 语句(我相信因为它会进入状态 2,然后进入状态 4),然后运行 ​​xhr.responseText。不幸的是,它似乎没有正确运行 upload.php(这可能是一个 php 问题)。我继续用打印语句替换了 php,当运行 alert(xhr.response.Text) 时会出现一个空白的警报语句,我不知道问题出在哪里。下面是我的表单代码、ajax 代码和我试图从中获得响应的 php 代码。

有人看到我遇到的问题吗?我是 AJAX 的新手,有一段时间没有使用 PHP。我正在努力提高我的 ajax/javascript 技能,但在我看来,它似乎没有正确获取 ajax。

HTML代码

> <form action="scripts/upload.php" method="post"
> enctype="multipart/form-data">
>       <label>Select a File to Upload</label> <input id="upload_file" type="file" name="upload_file" /> 
>       <input type="button" onclick="loadFile()" value="Upload"  />    </form>

JavaScript/AJAX 代码

//LOAD IMAGES THROUGH JAVASCRIPT WINDOW.ONLOAD = INIT();

$(document).ready(function() {
  // Handler for .ready() called.

  $('.heading').click(function() {
      if($(this).find('li').is(':visible')) {   
        $(this).find('li').slideUp('slow'); 
    }else {
      $('.heading').find('li').slideUp('slow');
      $(this).find('li').slideDown('slow'); 
    }
  })
});

var xhr = createRequest();

function loadFile() {
//retrieve the FileList object from the referenced element ID
    var myFileList = document.getElementById('upload_file').files;

    //grab the first file object from the filelist
    var myFile = myFileList[0];

    //set some variables containing attributes of file
    var myFileName = myFile.name;
    var myFileSize = myFile.size;
    var myFileType = myFile.type;

    //alert the information gathered and if it is right
    alert("FileName: " + myFileName + "- FileSize: " + myFileSize + " - FileType: " + myFileType);

    //check above by alert if file size is below a certain MB and of image type JPEG, PNG, GIF

    //Let's upload the complete file object
    uploadFile(myFile);
}

function uploadFile(myFileObject) {
    // Open Our formData Object
    var formData = new FormData();

    // Append our file to the formData object
    // Notice the first argument "file" and keep it in mind
    formData.append('my_uploaded_file', myFileObject);

    // Create our XMLHttpRequest Object
    xhr.onreadystatechange = addImage;

    // Open our connection using the POST method
    xhr.open("POST", 'upload.php');
    //Send the proper header information along with the request
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // Send the file
    xhr.send(formData);
}

function addImage() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        alert("WIN");
        alert(xhr.responseText);
    } else {
        alert("ERROR ERROR: " + xhr.status);
    }
}

AJAX 请求代码

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  } 
  return request;
}

PHP 代码

<?php
    echo "hello";
?>

<?php
/*
define("UPLOAD_DIR", "../images");

if (!empty($_FILES["myFile"])) {
    $myFile = $_FILES["myFile"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }

    // ensure a safe filename
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // don't overwrite an existing file
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // preserve file from temporary directory
    $success = move_uploaded_file($myFile["tmp_name"],
        UPLOAD_DIR . $name);
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    }

    // set proper permissions on the new file
    chmod(UPLOAD_DIR . $name, 0644);
}
*/
?>

我粘贴了我所有的 PHP 代码,虽然现在我只是使用 echo PHP 代码来获得响应,但我确信我的上传 PHP 代码有很多东西(除了安全检查之外)。但是,如果你们能指出我正确的方向或帮助我弄清楚 ajax 调用是否有效或为什么无效。我个人认为它只是没有 responseText。这是我第一次使用 Ajax 创建我自己的要运行的 PHP 代码。

最佳答案

在您的表单的 action 属性中,您有 scripts/upload.php 但 ajax url 是 upload.php。

不要设置内容类型标题,当你传递 formdata 时它会自动设置为 multipart/form-data反对 XMLHttpRequest.send

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".

关于php - AJAX/Javascript 上传 PHP 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14307829/

相关文章:

javascript - php中的相对url

java - 上传文件到 PHP 源时发送参数

javascript - React Native 渲染相同的路线

javascript - Web 应用程序的推送通知

javascript - 快速需要 Flash/Lightwindow 帮助

javascript - 在带有 createTextNode 的段落上使用 <span>

javascript - 从 Chrome 扩展后台页面发送的 AJAX 请求是否发送引荐来源网址?

java - Google 方向 api 跳过有关小转弯的信息

javascript - jquery非法调用错误

php - 如何允许用户名使用特殊字符?