Php / ajax文件上传:隐藏的iframe加载多次

时间:2012-01-31 11:45:20

标签: php jquery ajax

当我使用ajax上传图片时,我的问题就出现了。 Ajax响应来自一个隐藏的iframe,对于调试我在这里回显它(上传的图像名称),然后提醒它。因此,当我上传第一张图片时 - 应该有一个警报。当我上传第二个 - 我看到2个警报。 3 - 3警报。等等。这意味着,我的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

...

1 个答案:

答案 0 :(得分:1)

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

我认为问题出在这里。在表单提交上添加一个“on load”事件。所以它调用了1次,然后是2次,等等。也许删除这两个字符串中的第一个可以帮助(仅使用加载事件处理程序)。