透過Iframe上傳檔案
將Form要送出的目標改為動態建立的IFrame,好處在於跟Ajax一樣可以在不刷新頁面的前提下送出資料,但無法很方便取得Json結果,只能將Iframe的document資料去手動解晰成JSON格式。
Jquery
function ajax_form($form, on_complete)
{
var iframe;
if (!$form.attr('target'))
{
//create a unique iframe for the form
iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
$form.attr('target', iframe.attr('name'));
}
if (on_complete)
{
iframe = iframe || $('iframe[name=" ' + $form.attr('target') + ' "]');
iframe.load(function ()
{
//get the server response
var response = iframe.contents().find('body').text();
on_complete(response);
});
}
}