jQuery AJAX调用两次

时间:2018-07-20 01:00:39

标签: jquery ajax

它一直在调用ajax,第一次工作正常,然后第二次第一次上传2次,然后第二次,第二次上传3次,只是不断增加并上传较旧的图像。

      $(".imageUploadIcon").on('click', function(ev){
      var readyflag = true;
      if (readyflag == true){
        ev.preventDefault();
        var fd = new FormData();
          var imgid = $(this).data('img-id');
          $('#imgupload').click();
          var uid = <?php echo $_GET['user']; ?>;
          fd.append('uid', uid);
          fd.append('imgid', imgid);
        $("#imgupload").change(function (){
         var image = $('#imgupload')[0].files[0];
         fd.append('image',image);
        $("#img"+imgid).attr('src','img/loader.gif');
            $.ajax({
                type: "POST",
                url: "php/usrIMG.php",
                data: fd,
                processData: false,
                contentType: false,
                success: function (data) {
                  $("#img"+imgid).attr('src','../../'+data);
                  Materialize.toast('Image uploaded successfully!', 4000);
                  eadyflag = false;
                  imgid = '';
                  image = '';
                  $('#imgupload').val("");
              }
            });


      });
    }
  });

1 个答案:

答案 0 :(得分:0)

这是因为每次单击#imgupload元素时,您都会在.imageUploadIcon元素上注册新的更改处理程序。

您应该能够将$("#imgupload").change()逻辑与.on('click', ..)逻辑解耦以解决此问题。

此处的解耦意味着您需要将imgid的数据.imageUploadIcon发送到#imgupload元素。一种方法是使用jQuery的.data()方法,如下所示:

$("#imgupload").change(function () {
    var image = $('#imgupload')[0].files[0];

    // Decouple the logic by exhanging 'imgid' via jQuery's data()
    // method. Here we are getting the 'imgid' that was set on 
    // #imgupload during .on('click',..)
    var imgid = $('#imgupload').data('imgid');

    var uid = <? php echo $_GET['user']; ?>;

    var fd = new FormData();
    fd.append('uid', uid);
    fd.append('imgid', imgid);
    fd.append('image', image);

    $("#img" + imgid).attr('src', 'img/loader.gif');
    $.ajax({
        type: "POST",
        url: "php/usrIMG.php",
        data: fd,
        processData: false,
        contentType: false,
        success: function (data) {
            $("#img" + imgid).attr('src', '../../' + data);
            Materialize.toast('Image uploaded successfully!', 4000);
            eadyflag = false;
            imgid = '';
            image = '';
            $('#imgupload').val("");
        }
    });
});


$(".imageUploadIcon").on('click', function (ev) {
    var readyflag = true;
    if (readyflag == true) {
        ev.preventDefault();

        var imgid = $(this).data('img-id');

        // Set the imgid as custom data on #imgupload to decouple the 
        // logic the imgid can then be accessed in the #imgupload 
        // change() handler
        $('#imgupload').data('imgid', imgid)
        $('#imgupload').click();
    }
});

有关jQuery .data()方法see the documentation here

的更多信息