Post请求图片时非法调用

Illegal invocation when Post request an image

我正在尝试对图像执行 post 请求,但是当我将其添加为参数 Uncaught TypeError: Illegal invocation 时,我一直收到以下错误。我试过这个和 .serialize(),但似乎没有任何效果。

  var description = $('#description').val();
  var title = $('#title').val();

  var fileInput = $("#image")[0];

  var file = fileInput.files[0];
  var image = new FormData();
  image.append('image', file);

  $.ajax({
    type: 'POST',
    url: 'insert.php',
    data: {
        desc: description,
        title: title,
        image:image,
        longitude: currentMarker.lng(),
        longitude: currentMarker.lat(),
           },
          success: function (answer) {

          }
      })

您不能将 FormData 放入要发送的参数之一,它必须是整个 data 值。所以应该是:

var image = new FormData();
image.append('image', file);
image.append('desc', description);
image.append('title', title);
image.append('longitude', currentMarker.lng());
image.append('latitude', currentMarker.lat());
$.ajax({
    type: 'POST',
    url: 'insert.php',
    data: image,
    processData: false,
    contentType: false,
    success: function(answer) {
        ...
    }
});

发送 FormData 时,您需要告诉 jQuery 不要尝试将数据参数从对象转换为使用 processData: false 的 URL 编码字符串。