我已经有一个使用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 input.files信息,但我无法通过php。$ _ FILE传递它。请给我一些示例代码,将输入类型的文本和文件结合起来,而无需使用form标记和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);
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句