[伪·Ajax]无刷新上传原理

| No Comments | No TrackBacks
首先,Ajax是JavaScript-Based, 决定运行于浏览器中的它基本没法操作独立本地文件, 之所以说是伪·Ajax,因为是利用iframe来实现无刷新上传的。
无刷新的本质是在原先的Form中插入一个不可见的iFrame, 并且把原Form增加一个Target="$iFrame->Name && id", 通过操作这个iFrame来实现整体的面刷新, 并通过返回给iFrame的值来操作父级对象实现callback操作。
下面是关键代码
Head区的Javascript
<script language="javascript" type="text/javascript">
function startUpload(){
      document.getElementById('f1_upload_process').style.visibility = 'visible';
      document.getElementById('f1_upload_form').style.visibility = 'hidden';
      return true;
}
function stopUpload(success){
      var result = '';
      if (success == 1){
         result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
      }
      else {
         result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
      }
      document.getElementById('f1_upload_process').style.visibility = 'hidden';
      document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
      document.getElementById('f1_upload_form').style.visibility = 'visible';     
      return true;  
}
</script>


相关的html代码
<div id="content">
                <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
                     <p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
                     <p id="f1_upload_form" align="center"><br/>
                         <label>File: 
                              <input name="myfile" type="file" size="30" />
                         </label>
                         <label>
                             <input type="submit" name="submitBtn" class="sbtn" value="Upload" />
                         </label>
                     </p>
                     <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
                 </form>
 </div>


处理的upload.php的功能代码
<?php
   // handle FileUpload Issues
    bla~bla~bla~
   if($UPLOAD_ALLOK == TRUE) {
      $result = 1;
   }
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>

最终还是回归了iFrame......哎, 自己来实现浏览器的Form操作的想法实在是太可耻了

No TrackBacks

TrackBack URL: http://blog.suchasplus.com/mt/mt-tb.cgi/202

Leave a comment

About this Entry

This page contains a single entry by suchasplus published on October 6, 2008 3:00 PM.

其实大家都是历史人物 was the previous entry in this blog.

攒RP攒RP - 记几则好人好事 - 囧 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Pages

OpenID accepted here Learn more about OpenID
Powered by Movable Type 5.2.7