使用ajax与其他类型的输入发送文件


send file using ajax with other type of input

我已经有了一个使用ajax将数据保存到数据库的表单。我有这个样本

Html代码

<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>

Javascrip代码

$("#btnSave").click(function(){
    p_name = $("#product_name").val();
    p_des = $("#product_description").val();
    p_image = $("#product_img").prop('files')[0];
    data = {
       'product_name':p_name,
       'product_description':p_des
    }
   $.post('url_here',data,function(response){
       console.log(response);
   });
});

我有这个信息Jquery输入。但我不能让它作为$_FILE传递给php。请给我一些例子代码结合输入类型文本和文件不使用表单标签和使用jquery ajax

您可以使用FormData:

document.getElementById('btnSave').addEventListener('click', function() {
  var fd = new FormData();
  fd.append('product_name', document.getElementById('product_name').value);
  fd.append('product_description', document.getElementById('product_description').value);
  fd.append('product_name', document.getElementById('product_img').files[0]);
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'url_here');
  xhr.addEventListener('load', function(e) {
    console.log(xhr.responseText);
  });
  xhr.send(fd);
});

既然你想使用jQuery AJAX(我不知道为什么,因为它不准备使用XHR2),你可以通过告诉它不处理data参数来解决问题,例如:

$('#btnSave').click(function() {
  p_name = $('#product_name').val();
  p_des = $('#product_description').val();
  p_image = $('#product_img').prop('files')[0];
  var data = new FormData();
  data.append('product_name', p_name);
  data.append('product_description', p_des);
  data.appned('product_img', p_image);

  $.ajax({
    url: 'url_here',
    data: data,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(response){
      console.log(response);
    }
  });
});