2012-01-31 52 views
0

我上傳圖片的時候發生了問題,我用ajax上傳圖片。 Ajax響應來自一個隱藏的iframe,爲了調試,我在這裏迴應它(上傳的圖像名稱),然後提醒它。因此,當我上傳第一張圖片時 - 應該有一個警報。當我上傳第二個 - 我看到兩個警報。第3 - 3個警報。等等。這意味着,我的iframe會重新加載多次,就像上傳文件的訂單號一樣。Php/ajax文件上傳:隱藏iframe加載不止一次

有趣的是,每個文件上傳後警報中的名稱始終相同。例如,2次「mySecondImage.jpg」,3次「myThirdImage.jpg」...

可以做些什麼來解決問題?謝謝。

// FUNCTION - AJAX FILE UPLOADER 
// this function creates new elements, but only in case, when user uploads files 
$.fn.fileUploader = function ($inputName) { 

    var $body = $(this); 
    var $form = $body.parents('form'); 
    var $fileInput = $body.find(':file'); 
    // after file is uploaded, we need the file input to be empty again 
    var $fileInputEmpty = '<input type="file" name="' + $inputName + '" />'; 
    var $iframe = $('#ajaxResult'); 

    // user submits the form 
    $form.submit(function() { 
    // check the result 
    $iframe.load(function() { 
     var $response = $iframe.contents().find('body').html(); 
     alert($response); // debug 

     // add new content image 
     $output = createUpdateImage($response, $('[name="imageLinkURL"]').val()); 

     // add new element 
     addNewElement($output); 

     // success 
     if ($response.length) { 
     $fileInput.replaceWith($fileInputEmpty); 
     $fileInput = $body.find(':file'); 
     } 
    }); 
    }); // form submit 

}; 

$('.fileUploder').each(function() { 
    var $inputName = $(this).find(':file').attr('name'); 
    $(this).fileUploader($inputName); 
}); 

那麼,小故障是固定的! 我稍微改寫了jQuery函數:

... 

// user submits the form 
$form.submit(function() { 

    var $response = ''; 

    $iframe.load(function() { 
    $response = $iframe.contents().find('body').html(); 
    }); 

    // periodically check the result in iframe 
    var $timer = setInterval(function() { 
    if ($response != '') { 
     clearInterval($timer); 
     // do all required actions 
    } 
    }, 100); 

}); // form submit 

... 
+0

讓我搜索我的水晶球,看看。 – hakre 2012-01-31 11:49:42

+0

發佈代碼,我們可以幫助你。 – 2012-01-31 11:58:18

回答

1
$form.submit(function() { 
    $iframe.load(function() { 

我覺得問題就在這裏。在表單提交您添加一個事件「上載」。所以它調用1次,然後2次,等等。也許刪除這兩個字符串的第一個可以幫助(只使用加載事件處理程序)。

+0

我刪除了onsubmit函數。現在我總是看到2個警報,儘管上傳文件的訂單號碼。 – Webars 2012-01-31 12:52:42

+0

也許有一個以上的錯誤,我只注意到這一個。但現在他們的人數不再增長) – Eddie 2012-01-31 14:03:17

+0

埃迪,你的通知指出了我的問題的根源。我添加了工作代碼。非常感謝你! – Webars 2012-01-31 14:29:02