$.ajax 和 php 回复

$.ajax and php responses

当我以这种方式发出请求时,我从来没有得到对 manipulate 的响应。 好吧,我得到回应 ***大批 ( [名称] => 精通React Native(二).pdf [类型] => application/pdf ... 但我需要向用户显示文件信息。

  <form id='formid'>
        <input id='fileid' type='file' name='file1' hidden/>
        <input type='submit' value='IMPORT'/>
    </form>
    <script>
        $(document).on("submit", "form", function (e) {
            e.preventDefault();
            var fdat = new FormData(this);
            fdat.append('operation', 'IMPORT');
            function importFile() {
                return $.ajax({
                    url: "data-source/oracle_controller_upload.php",
                    type: 'POST',
                    dataType: "JSON",
                    data: fdat,
                    processData: false,
                    contentType: false,
                    success: function(response){
                                   }
                });
            }
            debugger;
            importFile().done(function (result) {
            }).fail(function () {
            });
        });
    </script>

这是我的 php 代码:

if (@$_REQUEST['operation'] === "IMPORT" && $_FILES) {
    echo print_r($_FILES['file1']);
    return;
}

无法到达 成功回调done()。 有帮助吗?

已解决

if (@$_REQUEST['operation'] === "IMPORT" && $_FILES) {
  echo json_encode($_FILES['file1']);
  return;
}

我有dataType: "JSON",所以回复当然是JSON.

你没有说清楚,但我想你一定是得到了关于无效 JSON 响应的错误。您的 ajax 请求期望从服务器返回 JSON,但您只是发送变量的原始字符串转储。

在 PHP 中,执​​行此操作:

if (@$_REQUEST['operation'] === "IMPORT" && $_FILES) {
    echo json_encode($_FILES['file1']); //encode the object as JSON instead of just a variable dump
    return;
}

并在您的 .done() 方法中:

importFile().done(function (result) {
  alert(result.name); //just for example, to display the name in an alert
  //...etc