AJAX:结合上传文件和文本输入代码?

时间:2015-01-20 15:08:48

标签: javascript jquery ajax file-upload

我正在使用jQuery和Ajax为我的表单提交数据和文件,但我不确定如何以一种形式发送数据和文件?

我有这样的代码:

$("#save-sm").bind("click", function(event) {
  var url = "sm.input.php";

  var v_name_sm = $('input:text[name=name_sm]').val();

  // sending for process
  $.post(url, {name_sm: v_name_sm, id: id_sm} ,function() {

    // show data <div id="data-sm"></div>
    $("#data-sm").load(main);

    // hide modal dialog
    $('#dialog-sm').modal('hide');

  });
});

我希望添加文件上传脚本,如下所示:

$("form#data").submit(function(){

  var formData = new FormData($(this)[0]);

  $.ajax({
    url: window.location.pathname,
    type: 'POST',
    data: formData,
    async: false,
    success: function (data) {
      alert(data)
    },
    cache: false,
    contentType: false,
    processData: false
  });

  return false;
});

如何将所有代码组合在一起,以便我可以一次发送两个?

谢谢:D


好的,这是我的最终代码:

$("#save-sm").bind("click", function(event) {

  var v_name_sm = $('input:text[name=name_sm]').val();
  var id_sm = "your variable";
  var formData = new FormData(document.getElementById("form-sm"));
  formData.append("name_sn",v_name_sm);
  formData.append("id",id_sm);

  $.ajax({
    url: 'sm.input.php',
    type: 'POST',
    data: formData,
    async: false,
    enctype: 'multipart/form-data',
    success: function () {
      // show data <div id="data-sm"></div>
      $("#data-sm").load(main);
      // hide modal dialog
      $('#dialog-sm').modal('hide');
    },
    cache: false,
    contentType: false,
    processData: false
  });

  return false;
});

1 个答案:

答案 0 :(得分:1)

您可以尝试以下内容:

$("form#data").submit(function(){

  var v_name_sm = $('input:text[name=name_sm]').val();
  var id_sm = "your variable";
  var formData = new FormData($(this)[0]);
  formData.append("name_sn",v_name_sm);
  formData.append("id",id_sm);
  $.ajax({
    url: window.location.pathname,
    type: 'POST',
    data: formData,
    async: false,
    enctype: 'multipart/form-data',
    success: function (data) {
      alert(data)
    },
    cache: false,
    contentType: false,
    processData: false
  });

  return false;
});