如何在不使用jQuery提交表单的情况下发布表单数据?

时间:2014-09-09 03:31:32

标签: jquery forms post

我正在尝试为我的帐户管理页面创建文件上传功能。我希望能够在不提交表单的情况下上传文件。我正在使用CodeIgniter的服务器端上传脚本。每次运行脚本时,文件输入字段为空。如何将一个特定输入的表单数据发送到我的ajax文件?

<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);
            })
        }
    });

});

1 个答案:

答案 0 :(得分:1)

试试这个:

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]);
    }
}

您可以添加其他参数:

formdata = $("#" + formId + "").serialize() + "&ProductId=" + productId + "&Sku=" + sku + "&IsVideo=" + isVideo;