[英]How can I upload a file using jquery's $.ajax function with json and php
我正在尝试使用 jQuery 的$.ajax
函数上传文件,但没有得到任何输出。 有人请帮我解决这个问题。 我不知道这个脚本是否正确。 我的脚本是:
$.ajax({
url:'newsup.php',
data: "",
type: 'POST',
contentType:'multipart/form-data',
dataType: 'json',
catche: 'false',
success:function(data6)
{
$("#disp").removeClass().addClass((data6.error=== false)? 'success':'error').html(data6.msg).fadeIn('fast');
//dele();
if($("#disp").hasClass('success'))
{
alert("success");
setTimeout("$('#disp').fadeOut('slow')",3000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown)
{
$("#disp").removeClass().addClass('error').html("There was an <strong>"+errorThrown+"</strong> error due to <strong>"+textStatus+" condition").fadeIn('fast');
}
});
此外,我需要帮助使用 jQuery 从文件上传字段获取数据。
请为此使用插件。
在我看来,这个插件是更好的解决方案。您不需要记住所有选项等。只需将您的“ajax”替换为“ajaxForm”。
我就是这样做的。 使用 FormData 对象。
注意:for 语句的奇怪语法只是将 "f" 设置为 array[i] 实例。
$("#submit").click(function () {
var formData = new FormData();
for (var i = 0, f; f = fileArray[i]; i++) {
formData.append("opmlFile", f);
}
$.ajax({
url: "/Documents/SaveFiles/" + @Model,
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false
})
.error(function (xhr, status, error) {
$.notify(error, true);
})
.success(function (data, status, xhr) {
$.notify("Success");
});
});
不幸的是,我不记得这是从哪篇文章中得到的,但它是 Stack Overflow 上的其他人。
AJAX 不支持文件上传。 有像ajaxfileupload这样的插件,它基本上创建一个隐藏的表单并动态上传你的文件。
看看这里并阅读 Oli 的回答
我正在使用它并且它工作正常:
$('#btnUploadFile').on('click', function () {
var data = new FormData();
var files = $("#fileUpload").get(0).files;
// Add the uploaded file content to the form data collection
if (files.length > 0) {
data.append("upload", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/documents",
contentType: false,
processData: false,
data: data,
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
console.log(data);
}
});
ajaxRequest.done(function (xhr, textStatus) {
$("#response").attr('class', "alert alert-success");
$("#response").html("File uploaded successfully");
});
});
Ajax 支持使用 FormData 对象上传文件,也支持除 IE8/9 之外的所有主流浏览器 见下文
另一种选择是对文件内容进行 base64 编码并将其作为字符串发送,在后端对其进行解码。
只需在表单上使用提交事件即可发送文件并防止默认表单操作
$('#form').submit(function(e) { return false; });
并通过服务器端获取文件
$_FILES['inputName'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.