如何在不使用jQuery提交表单的情况下发布表单数据?
我正在尝试为我的帐户管理页面创建文件上载功能。我想能够上传一个文件而不提交表格。我正在使用带有CodeIgniter的服务器端上传脚本。每次运行脚本时,文件输入字段都是空的。如何将一个特定输入的表单数据发送到ajax文件如何在不使用jQuery提交表单的情况下发布表单数据?,jquery,forms,post,Jquery,Forms,Post,我正在尝试为我的帐户管理页面创建文件上载功能。我想能够上传一个文件而不提交表格。我正在使用带有CodeIgniter的服务器端上传脚本。每次运行脚本时,文件输入字段都是空的。如何将一个特定输入的表单数据发送到ajax文件 <img src=".../attachments/f8725841986a40061b0f4da9f7ee45dd.png" width="100" height="100" border="0" alt="Avatar Not Available" src="..."
<img src=".../attachments/f8725841986a40061b0f4da9f7ee45dd.png" width="100" height="100" border="0" alt="Avatar Not Available" src="..." id="avatar_response"/>
<input type="file" name="avatar" size="30"><a href="javascript:void(0);" rel="submitFile" data-input-name="avatar">Save</a>
$(document).on('click', '[rel="submitFile"]', function(){
console.log('anchor clicked');
var $anchor = $(this);
var input_name = $anchor.data('input-name');
var file_input = $('#'+input_name+'_file');
console.log(file_input);
var postdata = new FormData();
var files = file_input.files;
console.log(files);
postdata.append(input_name, files[0]);
$.ajax({
type: "POST",
url: "http://basecommand/index.php/ajax/upload/avatar/"+input_name,
dataType: "xml",
contentType: false,
processData: false,
statusCode: {
404: function(){
console.log("The file was not found.");
}
},
error: function(jqXHR, textStatus){
console.log("AJAX Error: "+textStatus);
},
success: function(xml)
{
console.log("ajax successful");
$(xml).find("upload").each(function(){
var fileurl = $(this).find("fileurl").text();
var response = $(this).find("response").text();
console.log(fileurl);
console.log(response);
})
}
});
});
$(文档)。在('click','rel=“submitFile”]'上,函数(){
log('anchor clicked');
var$anchor=$(此);
var input_name=$anchor.data('input-name');
var file_input=$('#'+输入_名称+''文件');
console.log(文件输入);
var postdata=new FormData();
var files=file\u input.files;
console.log(文件);
append(输入_名称,文件[0]);
$.ajax({
类型:“POST”,
url:“http://basecommand/index.php/ajax/upload/avatar/“+输入_名称,
数据类型:“xml”,
contentType:false,
processData:false,
状态代码:{
404:函数(){
log(“未找到该文件”);
}
},
错误:函数(jqXHR,textStatus){
log(“AJAX错误:+textStatus”);
},
成功:函数(xml)
{
log(“ajax成功”);
$(xml).find(“upload”).each(函数(){
var fileurl=$(this.find(“fileurl”).text();
var response=$(this.find(“response”).text();
log(fileurl);
控制台日志(响应);
})
}
});
});
试试这个:
var postdata = new FormData();
if (formId == "imageForm") {
var filesList = document.getElementById('imgFile');
for (var i = 0; i < filesList.files.length; i++) {
postdata.append('file', filesList.files[i]);
}
}
去掉
href=“javascript:void(0);”
并添加返回false代码>在ajax
代码之后的单击函数末尾。文件可以通过ajax发送,但必须在HTML5的FormData
对象中创建。下面就是这个主题。您需要防止按钮单击的默认操作(可能是提交表单)。因此,要么从单击处理程序返回false,要么调用event.preventDefault()
其中event
是单击处理程序@Ohgodwhy的第一个参数。如果我将void(0)更改为返回false,我会不断收到错误“非法返回语句”。我还尝试了FormData对象,但我一直收到一个错误,说“无法读取未定义的属性“0”。我已经更新了我的代码。
formdata = $("#" + formId + "").serialize() + "&ProductId=" + productId + "&Sku=" + sku + "&IsVideo=" + isVideo;