dojo upload file 範例
dojo 要做 AJAX 方式的檔案上傳其實是透過 iframe 來實做才有辦法實做 , 因此 dojo 特別提供一組指令 dojo.io.iframe 方法很簡單 , 網頁範例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <script src="/xxx/dojo-path/dojo.js" djConfig="parseOnLoad: true, isDebug: false"></script> <script> dojo.require("dojo.parser"); dojo.require("dojo.io.iframe"); function doUpload() { dojo.io.iframe.send( { url: 'test.php', form: 'frm' , method: "post", handleAs: "json", load: function(obj , ioArgs) { alert( obj.message ); } , error: function(response, ioArgs) { console.debug(response); } ) } </script> <form method="post" id="frm" enctype="multipart/form-data"> 上傳的檔案 : <input type="file" name="upfile"> <button onclick="doUpload()">上傳</button> </form> |
在 Server 端要注意一點 , dojo 的方式是需要把回應的 ajax 內容(例如 json格式) 放到一個 <textarea> 內 所以 test.php 會如下
1 2 3 4 | <?php $response = array( 'status' => 'success' , 'message' => '成功' , ); echo "<textarea>" . json_encode( $response ) . "</textarea>"; ?> |
要注意 <form> 表單一定要有 method , 據我測試若不指定 method="POST" , FireFox 是會根據 dojo.io.iframe.send() 所指定的方式 POST 送出資料 , 但 IE7 會以 GET 送出
Categories: Dojo
近期迴響