您好,欢迎访问一九零五行业门户网

javascript - jQuery+ajax文件上传失败,什么原因?

html部分:
文件上传

后端php部分:ajax.php


js部分,用js上传的时候是成功的,但用jquery的时候出现了两种错误:
一种是用$.ajax方法:
$(function(){ $(.sub).click(function(){ var fd=new formdata($(#up)); $.ajax({ url: 'ajax.php' , type: 'post', data: fd, async: false, cache: false, contenttype: false, processdata: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); })})

报错说找不到$_files里的pic,为什么呢?
补充:这个地方搞定了,var fd=new formdata($(#up));需要写成:
var fd=new formdata($(#up)[0]);
具体可见:http://segmentfault.com/q/1010000004213457
和 http://segmentfault.com/a/1190000002938709
用$.post方法的时候:
$.post(ajax.php,fd,function(data){ console.log(data); })

报错:uncaught typeerror: illegal invocation
这又是为什么呢?
(jquery是1.7.1版本的)
回复内容: html部分:
文件上传

后端php部分:ajax.php


js部分,用js上传的时候是成功的,但用jquery的时候出现了两种错误:
一种是用$.ajax方法:
$(function(){ $(.sub).click(function(){ var fd=new formdata($(#up)); $.ajax({ url: 'ajax.php' , type: 'post', data: fd, async: false, cache: false, contenttype: false, processdata: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); })})

报错说找不到$_files里的pic,为什么呢?
补充:这个地方搞定了,var fd=new formdata($(#up));需要写成:
var fd=new formdata($(#up)[0]);
具体可见:http://segmentfault.com/q/1010000004213457
和 http://segmentfault.com/a/1190000002938709
用$.post方法的时候:
$.post(ajax.php,fd,function(data){ console.log(data); })

报错:uncaught typeerror: illegal invocation
这又是为什么呢?
(jquery是1.7.1版本的)
设置不对。
var data = new formdata();data.append('file', $('input[type=file]')[0].files[0]);$.ajax({ url: 'ajax.php', data: data, processdata: false, type: 'post' contenttype: 'multipart/form-data', mimetype: 'multipart/form-data', success: function (data) { alert(data); } });
ajax是不能上传附件的,如果需要上传附件请参考使用jquery form插件
ajax只能传输文本流,不能运输二进制的文件。
可参考我写的关于formdata不刷新上传文件
formdata
ajax不能上传文件,还有form上传文件的enctype属性是要有的
contenttype: false, processdata: false,
其它类似信息

推荐信息