如何使用jquery的$ .ajax函数和json和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 "+errorThrown+" error due to "+textStatus+" condition").fadeIn('fast'); } }); 

我还需要帮助使用jQuery从文件上传字段中获取数据。

AJAX不支持文件上传。 像ajaxfileupload这样的插件基本上会创建一个隐藏的表单并动态上传你的文件。

看看这里 ,看看奥利的回答

请使用插件。
在我看来这个插件是更好的解决方案。你不需要记住所有选项等。只需将你的’ajax’替换为’ajaxForm’。

请阅读下面的示例
http://jquery.malsup.com/form/#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上的其他人。

您可以使用两个插件Jquery File Upload Plugins 1或Jquery File Upload Plugins 2中的任何一个,并且此脚本没有错误。

希望能帮助到你

谢谢,拉希德

Ajax支持使用FormData Object上传文件,除了IE8 / 9外,还支持所有主流浏览器

https://developer.mozilla.org/en-US/docs/Web/API/FormData

我正在使用它并且工作正常:

  $('#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"); }); }); 

只需在表单上使用提交事件即可发送文件并阻止默认表单操作

$('#form').submit(function(e) { return false; });

并通过服务器端获取该文件

 $_FILES['inputName'];