代码之家  ›  专栏  ›  技术社区  ›  AdRock

在jQuery中的函数之间传递变量

  •  1
  • AdRock  · 技术社区  · 15 年前

    http://www.fengcool.com/2009/06/ajax-form-upload-local-image-file-without-refresh/

    我遇到的问题是从服务器中删除映像。

    php文件不是问题,我认为ajax调用正确(可能需要检查),但我需要知道如何将upload函数中创建的filename变量传递给remove函数。

    文件名在此处创建

    function addUpload(id,img){
    
       var loader = $(document.getElementById('loader'));
       loader.hide();
    
       var div = $(document.createElement('div')).attr('id',id).attr('class','uplimg');
    
       //add uploaded image
       div.html("<img src='/admin/"+img+"'><br />");
    
       //add text box
       fileName = img.substring(img.lastIndexOf("/")+1);
    

    function removeUpload(e){
    
    
       var removeId = $(e.target).attr('alt');
    
       alert(filename);
    
                //ajax call to unlink image using php
        /*$('#'+removeId).click(function(){
            $("#uploaded_thumb")
                .html(ajax_load)
                .load(loadUrl, {filename: filename});
        });
    
       $('#'+removeId).remove();
       if(fileCount>0) fileCount--;
       $("#inp").removeAttr('disabled'); */
    }
    

    如何将文件名从一个函数传递到另一个函数,我的ajax调用是否正确?我想在url中传递一个名为filename的变量,这个变量就是文件名

    var frameId = 'frame_ID';      //hidden frame id
    var jFrame = null;                //hidden frame object
    var formId = 'form_ID';         //hidden form id
    var jForm = null;                 //hidden form object
    var fileMax = 3;                  //maximum number of file to be uploaded
    var fileCount = 0;               //file counter
    var uploadUrl = "/admin/save.php"; //where to handle uploaded image
    var filename = null;
    var loadUrl = "/admin/load.php";
        var imgName='';
    
    $(document).ready(function(){                     
    
    jForm = createForm(formId);       //create hidden form
    jForm.hide(); 
    jFrame = createUploadIframe(frameId)   //create hidden iframe
    jFrame.hide();
    
    //append hidden form to hidden iframe
    jForm.appendTo('body');         
    jForm.attr('target',frameId);              //make form target to iframe
    
    $("#inp").bind('change',startUpload);   //bind onchange function to input element
    
    function startUpload(){
       if(jForm!=null){               
          jForm.remove();                        //re-create hidden form
          jForm = createForm(formId);
          jForm.appendTo('body');
          jForm.attr('target',frameId);
       }
    
       document.getElementById('loader').style.display="block";
    
       var newElement = $(this).clone(true);   //clone input element object
       newElement.bind('change',startUpload); //bind onchange function. detect iframe changes
       newElement.insertAfter($(this));          //insert clone object to current input element object
       $(this).appendTo(jForm);
    
       jForm.hide();                   
       jForm.submit();                     //let's upload the file
    
       jFrame.unbind('load');                  
       jFrame.load(function(){               //bind onload function to hidden iframe
    
          //get response message from hidden iframe
          var myFrame = document.getElementById($(this).attr('name'));   
          var response = $(myFrame.contentWindow.document.body).text();
    
          /*
          * you may handle upload status from reponse message.
          * in this example, upload succeeded if message contains ".gif" , otherwise, alert reponse message
          */
    
          if((response.indexOf('.jpg')) || (response.indexOf('.gif')) !=-1) { //upload successfully
    
             addUpload(Math.floor(Math.random()*100),response);   //show thumbnails, add text box with file name
             fileCount++;
             if(fileCount >= fileMax){                     //reach maximum upload file, disable input element
                $("#inp").attr('disabled','disable');
             }
          }else{  //error
             alert(response);
          }
       });
    }
    
    
    });
    
    function createUploadIframe(id){
       //set top and left to make form invisible
       return $('<iframe width="300" height="200" name="' + id + '" id="' + id + '"></iframe>')
             .css({position: 'absolute',top: '270px',left: '450px',border:'1px solid #f00'})
             .appendTo('body');
    }
    
    function createForm(formId) {
          return $('<form method="post" action="'+uploadUrl+'" name="' + formId + '" id="' + formId + 
                '" enctype="multipart/form-data" style="position:absolute;border:1px solid #f00;'+
                'width:300px;height:100px;left:450px;top:150px;padding:5px">' +
                '</form>');
    }
    
    
    function addUpload(id,img){
    
           imgName = img.substring(img.lastIndexOf("/")+1);
    
        var loader = $(document.getElementById('loader'));
        loader.hide();
    
       var div = $(document.createElement('div')).attr('id',id).attr('class','uplimg');
    
       //add uploaded image
       div.html("<img src='/admin/"+img+"'><br />");
    
       //add text box
       fileName = img.substring(img.lastIndexOf("/")+1);
       var txtbx = $(document.createElement('input')).attr('name','myimg').attr('type','text').val(fileName);
       /* you may want to change textbox to a hidden field in production */
       //var txtbx = $(document.createElement('input')).attr('name','img[]').attr('type','hidden').val(fileName);
       txtbx.appendTo(div);
    
       //add remove thumbnail link
       var rem = $(document.createElement('a'))
                                   .attr('alt',id)
                                   .attr('href','javascript:;')
                                   .text("Remove").click(removeUpload);      
       rem.appendTo(div);
    
    
       //add to the page
       div.appendTo("#uploaded_thumb");
    }
    
    function removeUpload(e){
    
       var removeId = $(e.target).attr('alt');
    
    
            //this should call the function to unlink the file (php)
        $('#'+removeId).click(function(){
            $("#uploaded_thumb")
                .html(ajax_load)
                .load(loadUrl, {filename: imgName});
        });
    
       $('#'+removeId).remove();
       if(fileCount>0) fileCount--;
       $("#inp").removeAttr('disabled');
    }
    

    更新:

    我试过用这个函数来替换removeUpload(),但仍然不起作用。它甚至不做警报框。

    我走对了吗?

    function removeUpload(e){
    
       var removeId = $(e.target).attr('alt');
    
        $.post("delete.php", {filename: imgName},
            function(data){
              alert("Deleted !!");
          });
    
    
       $('#'+removeId).remove();
       if(fileCount>0) fileCount--;
       $("#inp").removeAttr('disabled');
    }
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Sarfraz    15 年前

    <script> addUpload 功能:

    <script>
    imgName = '';
    

    添加上载 功能:

    function addUpload(id,img){
      imgName = img;
      ..............
    }
    

    稍后您可以访问 imgName

    更新:

       $('#'+removeId).click(function(){
            $("#uploaded_thumb")
                .html(ajax_load)
                .load(loadUrl, {filename: imgName});
        });
    

    用途:

    $('#'+removeId).click(function(){
      $.post("delete.php", {filename: imgName},
        function(data){
          alert("Deleted !!");
      });
    });
    

    稍后在脚本中,可以获得如下图像名称:

    $_POST['imgName']; // php
    Request.Form("imgName") // asp
    

    更多信息:

    http://api.jquery.com/jQuery.post/