weixin_33736832 2015-06-22 17:43 采纳率: 0%
浏览 17

拖放上传

I want to make drag and drop upload. User drops the files on div, and when he clicks on upload button, they are sent to server. javascript unfortunatelly does not know what variable fd is. How I can pass that variable to DragAndDropUpload() function.. Not sure if that is the real problem..

Im wondering whether to show you my website or not :D

here is my code(only important things , I removed the other things to make code look smaller)

Should I pass fd to function as an argument? o.O or what

$(document).ready(function(){
    var fd;
    var drag_area = $("#drag_and_drop_div");

    drag_area.on('drop', function(e){
        e.preventDefault();
        $("#nahraj_button").show();
        $("#upload_button").attr('onclick','DragAndDropUpload()');
        var files = e.originalEvent.dataTransfer.files; 
        fd = new FormData();
        fd.append('file[]',files[0]);
    });
});

function DragAndDropUpload(){
    var request = new XMLHttpRequest();
    request.open('POST', 'uploader.php');
    request.send(fd);
}

EDIT: Console shows this: Uncaught Reference error: fd is not defined

  • 写回答

2条回答 默认 最新

  • weixin_33720956 2015-06-22 17:57
    关注

    I think you have a problem with the scope of the variable fd. You define it within the scope of $(document).ready(function(){}); and later expect it to be set inside of your function DragAndDropUpload(). This will not work. You should pass it in the function.

    You also mixed up your events. You define the one event listener (for click) when the user drops something. You should do that outside.

    I don't know if the rest of your code is ok since you didn't include everything I need to know to answer that. Always say exactly which plugin you are using and which third-party scripts.

    And if you want to show something but not your website, use jsfiddle or codepen.

    $(document).ready(function(){
    
      // Document is ready, no user action yet
      var fd; // the fd variable sits inside the $(document).ready(function(){}) scope
      var drag_area = $("#drag_and_drop_div");
    
      drag_area.on('drop', function(e){
        e.preventDefault();
        $("#nahraj_button").show();
        var files = e.originalEvent.dataTransfer.files; 
        fd = new FormData();
        fd.append('file[]',files[0]); 
      });
    
      $("#upload_button").attr('onclick', function() {
        // now call you function and pass the form data as an argument
        DragAndDropUpload(fd);
      });
    
    });
    
    function DragAndDropUpload(data)
    {
      var request = new XMLHttpRequest();
      request.open('POST', 'uploader.php');
      request.send(data);
    }
    

    This article explains variable scopes in javascript a bit better.

    评论

报告相同问题?