使用 jquery ajax 上传文件的数据方法设置

Data method settings for file upload using jquery ajax

本文关键字:数据 方法 设置 文件 jquery ajax 使用      更新时间:2023-09-26

所以这个问题源于在使用 ajax 时缺乏对数据方法如何运作的良好理解。我已经在这里查看了有关ajax的大多数其他问题,但这部分不适合我。

例如,我使用 ajax 将表单数据(包括多个文本字段和一个文件上传)发送到 php。然后,服务器脚本在 sql 数据库中插入字段数据和文件 url,然后将所有这些值作为 json 编码数组返回。

我当前的ajax脚本如下所示,当它运行时,除了文件上传部分外,一切正常。文件没有保存到服务器,当然也没有url回来。 如果我更改:

data: data,

data: text,
文件

上传有效,文件被保存,但是当 JSON 数组返回到页面时,我会看到一个显示数组数据的白屏(它不会返回到表单数据来自的页面)。

这是为什么呢?使用什么正确的数据方法来允许我的文件上传工作并使数据返回到发送它的页面。

$("document").ready(function() {
$(".data-form").submit(function() {
        var data = new FormData();
$.each(files, function(key, value)
  { data.append(key, value);
});
    if (confirm("'t't'tAre you ready to sumbmit this listing?'nYou can always edit the listing after going to the menu tab - edit listing."))       {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "add-list.php",
            data: data,
            processData: false,
            contentType: false,
            success: function(response) {
                      if (response.success) {
                          $("#modal1").modal('hide');
                        $("#add_frame").show();
                        $("#newbutt").show();
                        $(".atitle").html('<a href="' + response.ad_linka + '" target="_blank">' + response.titlea + '</a>');
                        $(".acomment").html(response.commenta);
                        $(".aaddress").html(response.addressa);
                        $(".asale-price").html(response.sale_pricea);
                        $(".alease-price").html(response.lease_pricea);
                        $(".alot-size").html(response.lot_sizea);
                        $(".abuilding-size").html(response.build_sizea);
                        $(".azoning").html(response.zoninga);
                        }
                      else {
                          console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
                      }
                  },
                  error: function() {
                      alert("An Error has ocurred contacting the server. Please contact your system administrator");
                  }
              });
        return false;
    }
});
});

你需要告诉jquery停止处理你的数据

     processData: false, // Don't process the files
    contentType: false, // defaults to 'application/x-www-form-urlencoded; charset=UTF-8'

您没有发送构建数据的方式,但这样的事情应该可以工作

    var data = new FormData();
    $.each(files, function(key, value)
      { data.append(key, value);
    });