猿问

如何在 FormData 对象中捕获返回值

我正在使用 FormData 上传文件,如下所示


<script>



var form = document.forms.namedItem("excelForm");

form.addEventListener('submit', function(ev) {



  oData = new FormData(form);


oData.append("CustomField", "This is some extra data");


var oReq = new XMLHttpRequest();

oReq.open("POST", "excel", true);

oReq.onload = function(oEvent) {

    if (oReq.status == 200) {

        $("#downloadButton").attr("style", "visibility: visible;")

        alert(oReq.response)

    } else {


    alert(oReq.status)



     }

    };


  oReq.send(oData);

  ev.preventDefault();

}, false);

</script>

这将调用一个 php 函数,该函数将返回一个 vlue,所以我想捕获该值,我使用 oReq.response 来捕获该返回值,但它不起作用


这是我的 php 函数


     public function actionexcel()

    {


        //.........

            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {


//                re write the excel file

                $fileName =$date. basename($_FILES["fileToUpload"]["name"]);

                $newFile = $this->RewriteExcel($fileName);


               return $fileName;




            } else {

                echo ini_get('upload_max_filesize');

                echo "Sorry, there was an error uploading your file.";

            }

        }

        return $data;

    }


慕妹3242003
浏览 217回答 1
1回答

慕桂英4014372

在你的JavaScript 中:var form = document.forms.namedItem("excelForm");form.addEventListener('submit', function(ev){&nbsp; &nbsp; oData = new FormData(this);&nbsp; &nbsp; oData.append("CustomField", "This is some extra data");&nbsp; &nbsp; var oReq = new XMLHttpRequest();&nbsp; &nbsp; oReq.onreadystatechange= function(oEvent){&nbsp; &nbsp; &nbsp; &nbsp; if(this.readyState == 4 && this.status == 200){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#downloadButton").attr("style", "visibility: visible;")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(this.responseText)&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(this.status);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; oReq.send(oData);&nbsp; &nbsp; ev.preventDefault();}, false);&nbsp;// ensure that your php file is in the correct directory and is using '.php'oReq.open("POST", "./excel.php");// don't forget to sendoReq.send();在您的PHP文件中:// your class and method goes herepublic function actionexcel(){ ... }echo $class->actionexcel();
随时随地看视频慕课网APP
我要回答