【问题标题】:Detecting Failure with Javascript error event listener versus PHP return 1 in responseText使用 Javascript 错误事件侦听器检测失败与 PHP 在 responseText 中返回 1
【发布时间】:2012-11-18 18:53:51
【问题描述】:

xhr.upload.addEventListener("error", failed, false) 与我拥有$success = move_uploaded_file($tmp_name, $name); if $(success) { echo "0" } else { echo "1" } 有何不同?这是不必要的冗余吗?

function uploadPHP() {
    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("progress", updateProgress, false);
    xhr.upload.addEventListener("load", complete, false);
    xhr.upload.addEventListener("error", failed, false);
    xhr.upload.addEventListener("abort", cancelled, false);

    var foo = document.getElementById("uploadScreen");
    var form = document.getElementById("uploadForm");
    var percentComplete;
    var index;

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 1){
        }
--

    function cancelled() {
        //cancel
    }
}

localhost file_server # cat php/upload.php

<?php
//
//require_once('PhpConsole.php');
//PhpConsole::start();
$tmp_name = $_FILES['file1']['tmp_name'];
$path = "/trunk";
$name = $path . DIRECTORY_SEPARATOR . $_FILES['file1']['name'];
$success = move_uploaded_file($tmp_name, $name);
if ($success) {
echo "0";
} else {
    echo "1";
}
?>

【问题讨论】:

    标签: php javascript error-handling xmlhttprequest addeventlistener


    【解决方案1】:

    "error" 如果您的请求未通过(例如超时),则会发生。

    假设您需要验证一些数据。如果它无效,"error" 事件将不会发生,除非您在 PHP 中抛出未捕获的异常。相反,它只会返回一些指示值无效的数据,例如字符串"0"

    在您给定的示例中,move_uploaded_file 完全有可能失败,但错误处理程序不会触发,因为从技术上讲,请求已完成而没有意外事件。您想要采取的行动失败的唯一迹象是"0" 响应。

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多