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

时间:2010-07-31 14:04:28

标签: jquery ajax variables

我有一个我在这里找到的ajax图片上传脚本

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

我遇到的问题是从服务器上删除图像。

我在评论中读到我需要进行ajax调用来调用php文件来取消链接图像。

php文件不是问题,我想我的ajax调用正确(可能需要检查)但我需要知道如何将上传函数中创建的文件名变量传递给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的变量,它将是文件名

这是entre脚本

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()但它仍然无法正常工作。它甚至没有警报框。

我从jquery网站得到一个例子,因为理论上应该有一个附加到链接的点击事件,当调用该函数时,它只需要调用php脚本的ajax调用

我是在正确的轨道上吗?

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 个答案:

答案 0 :(得分:2)

在具有全局范围的<script>标记下方创建一个变量,以便稍后可以从addUpload函数为其指定图像的值:

<script>
imgName = '';

现在将此行添加到addUpload函数:

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/