当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Post multipart/form-data using Ajax

问题描述:

For some reason I can not get the following script to work correctly, when submitting the form without using the script all works as it should, but when using the script to submit the form I only get the category and description in the post variables but no file. So my question is how do I get the script to post the file variable also.

Ajax

$("#img-post").click(function()

{

$("#imgupload").submit(function(e)

{

var postData = $(this).serializeArray();

var formURL = $(this).attr("action");

$.ajax(

{

url : formURL,

type: "POST",

data : postData,

success:function(data, textStatus, jqXHR)

{

$("#img").html('<pre><code class="prettyprint">'+data+'</code></pre>');

},

error: function(jqXHR, textStatus, errorThrown)

{

alert('Error');

document.getElementById('enquiry').style.visibility = 'hidden';

}

});

e.preventDefault(); //STOP default action

});

$("#imgupload").submit(); //SUBMIT FORM

});

HTML

<div class="img" id="img"></div>

<form name="imgupload" id="imgupload" action="upload.php" method="post" enctype="multipart/form-data">

<input name="category" id="category" type="text" />

<input name="file" id="file" type="file" />

<textarea name="discription" id="discription" cols="68%" rows="8"></textarea><br>

<input type="button" id="img-post" name="img-post" value="Add" />

</form>

网友答案:

Data from file select elements is not serialized

Taken from the docs page at:

https://api.jquery.com/serializeArray/

However, you can achieve this with the jquery ajax form plugin found here:

http://malsup.com/jquery/form/

This plugin is nice because not only does it capture the form data (including files) you can easily send extra $_POST data in the data attribute of the ajax call along with your form.

分享给朋友:
您可能感兴趣的文章:
随机阅读: