ajax文件上传后的jQuery响应

时间:2016-02-18 10:55:10

标签: php jquery json ajax file-upload

我有一个带文件输入的简单表格 文件上传工作正常(我使用jQuery ajax& FormData),然后在我的PHP代码中我正在做一些处理然后返回一个json对象。 问题是ajax调用总是触发错误回调,因为parseerror,但json结构是正确的。

经过一些调试后,我注意到在responseText中有上传文件的内容(xslx),后面是在php页面中创建的正确的json对象。

这是我的表格:

<form method="POST" id="formImport" action="#">
  <div>
    <label for="upload_file" class="label_small">File</label>
    <input id="upload_file" type="file" name="upload_file" />
  </div>
  <input type="button" value="Upload" id="btnUpload" />
</form>

这是jQuery函数:

$('#btnUpload').unbind('click').click( function(e) {
  e.preventDefault();
  var formData = new FormData($('#formImport')[0]);
  formData.append('extraParam', '123');

  $.ajax({
    type: 'POST',
    url : 'upload.php',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    dataType : 'json',
    success: function(result) {
        console.log(JSON.stringify(result));
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // Here the responseText contains the file content before the correct json object
        alert("Error: jqXHR " + JSON.stringify(jqXHR) + " - textStatus " + JSON.stringify(textStatus) + " - errorThrown " + JSON.stringify(errorThrown));
    }
  });
});

编辑: php创建的json结构似乎是正确的;如果我在日志中打印它,这就是我所看到的:

{
  "ok": "0",
  "multipleMatch": [{
      "row": 22,
      "matches": [{
          "val": "161290348"
      }, {
          "val": "9613464"
      }]
  }, {
      "row": 35,
      "matches": [{
          "val": "395486129"
      }, {
          "val": "32056134"
      }]
  }]
} 

我找不到任何理由为什么它会在responseText中添加文件内容,不知道为什么会这样?谢谢!

0 个答案:

没有答案
相关问题