使用jquery $ .ajax和php上传文件

当用户在输入文件中使用$ .ajax选择文件时,我希望异步上传文件。 但是,回复调用返回索引的php未定义。 jquery代码是下一个:

$("#urlimatge").change(function(){ var filename = $("#urlimatge").val(); $.ajax({ type: "POST", url: "utils/uploadtempimg.php", enctype: 'multipart/form-data', data: {'urlimatge' : filename }, success: function(response){ alert(response); } }); }); 

以及重新调用的php:

 $image = new gestorimatges(); $target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']); 

谢谢

您无法使用AJAX上传文件,但您可以使用iframe因此您无需刷新当前页面。

很多人都去插件,但你可以很容易地自己做,并具有AJAX请求的所有function。

而不是使用AJAX函数,将表单提交给隐藏的iframe ,该iframe附加了一个load事件处理程序,因此在提交表单时,您有一个实际包含服务器响应的回调函数( iframe之后的iframe的HTML)负荷)。

例:

HTML –

 

JS –

 $(function () { $('form').on('submit', function () { //check if the form submission is valid, if so just let it submit //otherwise you could call `return false;` to stop the submission }); $('#workFrame').on('load', function () { //get the response from the server var response = $(this).contents().find('body').html(); //you can now access the server response in the `response` variable //this is the same as the success callback for a jQuery AJAX request }); }); 

你不能将$ _FILE从AJAX传递给PHP。

我建议使用一个插件

它将使您的生活更轻松:) 这是一个video教程也可以提供帮助

你可能想使用像uploadify这样的工具。