2011-11-26 197 views
1

我试图用jQuery上传文件。我使用了一个隐藏的表单,其中包含Input,然后我使用jQuery来触发文件浏览器。一旦输入被改变,文件就会被发布到PHP服务器脚本中。需要Jquery文件发布帮助

我的问题是,如果我只是做$("form1").submit();一切工作完美,但我的网页然后重定向。为了避免重定向,我想从PHP脚本中获取响应文本,因此我使用了jQuery Post函数,但是这次PHP脚本无法识别是否存在文件帖子,并且只要返回错误($_FILES) = nothing就会返回错误。

我的HTML代码:

<form id="form1" name="up1" method="POST" action="upload.php" enctype="multipart/form-data"> 
<input style="width:0px;height:0px"id="br" type="file" name="Filedata"/> 
</form> 

的jQuery:

$("#br").change(function() { 
    var $el = $('#br'); 
    $('#form1').submit(); 
}); 
//The code above works perfectly if I dont add this code below. 
$("#form1").submit(function(event) { 
event.preventDefault(); 
var $el = $('#br'); 
var $form = $(this), 
term = $form.find('input[name="Filedata"]').val(), 
url = $form.attr('action'), 
enctype= "multipart/form-data"; 

$.post(url, { s: term }, 
    function(data) { 
    alert(data); 
    } 
); 
}); 
+0

看看这个http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – Cyclonecode

回答

1

它不可能使用Ajax上传文件。但是,有一个窍门:创建一个隐藏的iframe并将该窗体的目标设置为iframe。使用iframe的readyState属性来告知fileupload何时完成。它不是真正的Ajax,但看起来就像它。