$ .ajax和php回复

时间:2017-11-09 13:26:47

标签: php ajax http-headers response

当我以这种方式提出请求时,我从未得到操纵的回应。 好吧,我得到了回应 ***阵列 (     [name] =>掌握React Native(2).pdf     [type] =>应用程序/ 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;
}

无法达到成功回调已完成()。 有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

解决了

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

我有dataType: "JSON",所以当然响应必须是JSON。

答案 1 :(得分:1)

您还没有确切地说,但我认为您必须收到有关无效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