可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
So I have a form and I\'m submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : \"POST\",
cache : false,
url : \"blah\",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type=\"file\">
field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn\'t output anything
回答1:
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There\'s a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$(\'#ifoftheform\').ajaxForm(function(result) {
alert(\'the form was successfully processed\');
});
});
The plugin automatically takes care of subscribing to the submit
event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
回答2:
You can now upload files with Ajax!
Examples:
https://stackoverflow.com/a/8758614/1072492
http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
回答3:
It works for any type of form
$(document).on(\"submit\", \"form\", function(event)
{
event.preventDefault();
var url=$(this).attr(\"action\");
$.ajax({
url: url,
type: $(this).attr(\"method\"),
dataType: \"JSON\",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
回答4:
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: \"ajax.php\",
type: \"POST\",
data: new FormData(\'form\'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$(\"#response\").html(data);
}
});
回答5:
var form = $(\'#job-request-form\')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: \"/send_resume/\", // the endpoint
type: \"POST\", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
回答6:
HTML
<form name=\"my_form\" id=\"my_form\" accept-charset=\"multipart/form-data\" onsubmit=\"return false\">
<input id=\"name\" name=\"name\" placeholder=\"Enter Name\" type=\"text\" value=\"\">
<textarea id=\"detail\" name=\"detail\" placeholder=\"Enter Detail\"></textarea>
<select name=\"gender\" id=\"gender\">
<option value=\"male\" selected=\"selected\">Male</option>
<option value=\"female\">Female</option>
</select>
<input type=\"file\" id=\"my_images\" name=\"my_images\" multiple=\"\" accept=\"image/x-png,image/gif,image/jpeg\"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $(\'#my_form\').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $(\'input[name=\"my_images\"]\')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append(\"my_images[]\", file_data[i]);
}
//Custom data
data.append(\'key\', \'value\');
$.ajax({
url: \"URL\",
method: \"post\",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo \'<pre>\';
print_r($_POST);
print_r($_FILES);
echo \'</pre>\';
die();
?>
回答7:
HTML5 introduces FormData
class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
https://developer.mozilla.org/en/docs/Web/API/FormData/FormData
回答8:
hmmmm i think there is much efficient way to make it specially for people want to target all browser and not only FormData supported browser
the idea to have hidden IFRAME on page and making normal submit for the From inside IFrame example
<FORM action=\'save_upload.php\' method=post
enctype=\'multipart/form-data\' target=hidden_upload>
<DIV><input
type=file name=\'upload_scn\' class=file_upload></DIV>
<INPUT
type=submit name=submit value=Upload /> <IFRAME id=hidden_upload
name=hidden_upload src=\'\' onLoad=\'uploadDone(\"hidden_upload\")\'
style=\'width:0;height:0;border:0px solid #fff\'></IFRAME>
</FORM>
most important to make a target of form the hidden iframe ID or name
and enctype multipart/form-data to allow accepting photos
javascript side
function getFrameByName(name) {
for (var i = 0; i < frames.length; i++)
if (frames[i].name == name)
return frames[i];
return null;
}
function uploadDone(name) {
var frame = getFrameByName(name);
if (frame) {
ret = frame.document.getElementsByTagName(\"body\")[0].innerHTML;
if (ret.length) {
var json = JSON.parse(ret);
// do what ever you want
}
}
}
server Side Example PHP
<?php
$target_filepath = \"/tmp/\" . basename($_FILES[\'upload_scn\'][\'name\']);
if (move_uploaded_file($_FILES[\'upload_scn\'][\'tmp_name\'], $target_filepath)) {
$result = ....
}
echo json_encode($result);
?>
回答9:
$(document).on(\'click\', \'#submitBtn\', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $(\"#myForm\").closest(\"form\");
var formData = new FormData(form[0]);
$.ajax({
type: \"POST\",
data: formData,
dataType: \"json\",
url: form.attr(\'action\'),
processData: false,
contentType: false,
success: function(data) {
alert(\'Sucess! Form data posted with file type of input also!\');
}
)};});
By making use of new FormData()
and setting processData: false, contentType:false
in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax