2012-04-21 87 views
2

上傳文件我希望在用戶在輸入文件中用$ .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); 
       } 
      }); 

     }); 

和recibe呼叫的PHP:

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

感謝

回答

1

你不能用AJAX上傳文件,但您可以使用一個iframe,所以你不必刷新當前頁面。

很多人都喜歡插件,但你可以很容易地做到這一點,並具備AJAX請求的所有功能。

而不是使用AJAX功能的,有一個表單提交到一個隱藏iframe具有附加給它一個load事件處理程序,以便提交表單的時候,你有,實際上包括服務器響應(的HTML的回調函數加載後iframe)。

例子:

HTML -

<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" > 
    <input type="file" name="file" /> 
    <input type="submit" /> 
</form> 
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe> 

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 
    }); 
}); 
+0

謝謝我對iframe使用了類似的解決方案。我調用iframe並使用jquery修改action的值。 – 2012-04-21 23:07:55

+0

以下不適用於我:我正在使用多文件上傳器來選擇多個文件。文件僅通過表單發送。它現在在我的Firefox瀏覽器中打開一個新的「標籤」.... \t

\t \t \t \t \t
rajeev 2012-12-19 01:16:47

+0