передача переменных между функциями в jQuery - PullRequest
1 голос
/ 31 июля 2010

У меня есть скрипт загрузки изображений ajax, который я нашел здесь

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

У меня проблема с удалением изображения с сервера.

Я прочитал в комментариях, что мне нужно сделать ajax-вызов, чтобы вызвать файл php, чтобы отсоединить изображение.

Файл php не является проблемой, и я думаю, что у меня есть ajaxвызов правильный (может потребоваться проверка), но мне нужно знать, как передать переменную имени файла, созданную в функции загрузки, в функцию удаления.

Здесь создается имя файла

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 переменную имени файла, которая будет именем файла

вот сценарий 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, потому что теоретически должно быть событие click, прикрепленное к ссылке, и когда функция вызывается, ей просто нужно вызвать ajaxпозвоните для сценария php

Я на правильном пути?

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 Ответ

2 голосов
/ 31 июля 2010

Создайте переменную чуть ниже тега <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/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...