我已经有一个使用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>
JavaScript 代码
$("#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 input.files equivalent但我无法让它作为 php 的 $_FILE 传递。请给我一些结合输入类型文本和文件的示例代码,而不使用表单标签和 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);
}
});
});
关于javascript - 使用 ajax 和其他类型的输入发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32971244/