【问题标题】:AJAX/Javascript with Upload PHP issue带有上传 PHP 问题的 AJAX/Javascript
【发布时间】:2012-12-27 18:52:16
【问题描述】:

我一直致力于制作一个通过 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,这可能是问题吗?
  • 您好,感谢您提供表单操作属性。我完全错过了,我很尴尬哈哈!现在 responseText 里面有 PHP 代码。

标签: php javascript ajax upload


【解决方案1】:

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

不要设置内容类型标头,当您将formdata 对象传递给XMLHttpRequest.send 时,它会自动设置为multipart/form-data。

FormData 对象允许您编译一组键/值对以使用 XMLHttpRequest 发送。它主要用于发送表单数据,但可以独立于表单使用以传输键控数据。如果表单的编码类型设置为 "multipart/form-data",则传输的数据与表单的 submit() 方法用于发送数据的格式相同。

【讨论】:

  • 谢谢你,我将不得不更多地查看标题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 2013-04-18
相关资源
最近更新 更多