我尝试使用Jquery和POST方法将多个图像上传到服务器。我试过这段代码但是我无法让它工作。有人帮我弄清楚代码有什么问题。 谢谢你的帮助。
function sendData2(){
$.fn.upload = function(remote, data, successFn, progressFn) {
// if we dont have post data, move it along
if (typeof data != "object") {
progressFn = successFn;
successFn = data;
}
var formData = new FormData();
var numFiles = 0;
this.each(function() {
var i, length = this.files.length;
numFiles += length;
for (i = 0; i < length; i++) {
formData.append(this.name, this.files[i]);
}
});
// if we have post data too
if (typeof data == "object") {
for (var i in data) {
formData.append(i, data[i]);
}
}
var def = new $.Deferred();
if (numFiles > 0) {
// do the ajax request
$.ajax({
url: 'http://URL?api_token=fb24085da58dad6decb9271fb170ef2ed8c80617',
type: "POST",
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload && progressFn){
myXhr.upload.addEventListener("progress", function(prog) {
var value = ~~((prog.loaded / prog.total) * 100);
// if we passed a progress function
if (typeof progressFn === "function") {
progressFn(prog, value);
// if we passed a progress element
} else if (progressFn) {
$(progressFn).val(value);
}
}, false);
}
return myXhr;
},
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
complete: function(res) {
var json;
try {
json = JSON.parse(res.responseText);
} catch(e) {
json = res.responseText;
}
if (typeof successFn === "function") successFn(json);
def.resolve(json);
}
});
} else {
def.reject();
}
return def.promise();
};
}
&#13;
div class="container">
<form method="post" action="upload.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter the Mune name">
</div>
<div class="form-group">
<label for="img">Upload menu's image:</label>
<input type="file" name="image" class="form-control" id="images" placeholder="choose image">
</div>
<input class="button green" type="submit" name="submit" value="Submit Content">
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<button type="button" onclick="sendData2()" class="btn btn-primary">Add Menue</button>
</form>
</div>
&#13;