找到你要的答案

Q:Ajax calls half working … file uploaded but javascript not executed

Q:Ajax调用半工作…但没有执行的JavaScript文件上传

I'm sorry for that question but I have a persistent bug and I don't understand at all what's happening ...

I have an ajax upload function that is working fine

function startUp(hash) {

    $('#file_up_form').ajaxForm({
                                beforeSend: function(xhr) {
                                    xhr.setRequestHeader("X-CSRF-Token", '{{ Session::token() }}' );
                                    xhr.setRequestHeader('Sha-Sha',hash);
                                    //other stuff
                                    },

                                uploadProgress: function(event, position, total, percentComplete) {
                                 //some stuff
                                },

                                complete : function(xhr) {
                                     //some stuff
                                },

                                error : function(xhr) {
                                    //some stuff
                                }

                            });
 }

When I call it that way :

$("#start_up_button").on('click', function() {

        if(checkFile()){

            startUp('f4274dd2284704f1158b2cecd71666a37ba5b949f97fc521974f98fa3dd0ea706cca7253244e20f2a4c4c694052097c45260edfe679c9e7b56896858a34839cd');
            //getHash();
        }

        else{
            $('#myModalerror').modal('show');
            $("#myModalerror").css("z-index", "1500");
        }
    }); 

Everything works fine. But when I uncomment the second line and comment the first to call it from :

function getHash(){

        input = document.getElementById('fileToUpload');

        file = input.files[0];
        var reader = new FileReader();

        reader.onload = function(e) {
            var shaObj = new jsSHA(reader.result,"BYTES");
            var hash = shaObj.getHash("SHA-512", "HEX");
            console.log(hash);
            startUp(hash);
        };
        reader.readAsBinaryString(file);

   }

Nothing work for ajax : the console.log display the correct hash but there are no headers set, and nothing from '//some stuff' works ... But the file is uploaded !! (??) I tried to wrap the call with a

setTimeout(function() {
                            startUp(hash);      
                                    }, 200);

but Firefox just crash. Any idea ??

thx

我很抱歉这个问题,但我有一个持久的错误,我不明白发生了什么事…

我有一个ajax上传功能工作正常

function startUp(hash) {

    $('#file_up_form').ajaxForm({
                                beforeSend: function(xhr) {
                                    xhr.setRequestHeader("X-CSRF-Token", '{{ Session::token() }}' );
                                    xhr.setRequestHeader('Sha-Sha',hash);
                                    //other stuff
                                    },

                                uploadProgress: function(event, position, total, percentComplete) {
                                 //some stuff
                                },

                                complete : function(xhr) {
                                     //some stuff
                                },

                                error : function(xhr) {
                                    //some stuff
                                }

                            });
 }

当我这样称呼它:

$("#start_up_button").on('click', function() {

        if(checkFile()){

            startUp('f4274dd2284704f1158b2cecd71666a37ba5b949f97fc521974f98fa3dd0ea706cca7253244e20f2a4c4c694052097c45260edfe679c9e7b56896858a34839cd');
            //getHash();
        }

        else{
            $('#myModalerror').modal('show');
            $("#myModalerror").css("z-index", "1500");
        }
    }); 

Everything works fine. But when I uncomment the second line and comment the first to call it from :

function getHash(){

        input = document.getElementById('fileToUpload');

        file = input.files[0];
        var reader = new FileReader();

        reader.onload = function(e) {
            var shaObj = new jsSHA(reader.result,"BYTES");
            var hash = shaObj.getHash("SHA-512", "HEX");
            console.log(hash);
            startUp(hash);
        };
        reader.readAsBinaryString(file);

   }

Ajax没有工作的console.log显示正确的哈希但没有头,没有从“/一些东西的作品…但文件上传!!(?)我试着用一个

setTimeout(function() {
                            startUp(hash);      
                                    }, 200);

但火狐只是崩溃。有什么想法吗??

谢谢

answer1: 回答1:

The behaviour of ajaxForm() in $('#file_up_form').ajaxForm({ ... }) is not to trigger an AJAX request.

It is an event binding function. (I've not gone through the API documentation, but probably it binds a form submit event to one of its inner library function)

To actually trigger an AJAX request you've to add a <input type="submit" > button inside the HTML <form>, and just click it. (Library will prevent traditional form submission, and submit it via AJAX)

Example implementation:

JS:

<script type="text/javascript">
$(document).ready(function(){
    $("#file_up_form").ajaxForm({ // bind library function to the form
        beforeSend: function(xhr){
            input = document.getElementById('fileToUpload');;

            file = input.files[0];

            if(file){
                var reader = new FileReader();
                reader.readAsBinaryString(file);

                var shaObj = new jsSHA(reader.result,"BYTES");
                var hash = shaObj.getHash("SHA-512", "HEX");

                xhr.setRequestHeader('Sha-Sha', hash);
            }else{
                alert("First, please select a file to upload.");
                return false;
            }
        },
        uploadProgress: function(event, position, total, percentComplete){ },
        success: function() { },
        complete: function(response) { },
        error: function() { }
    });
});
</script>

HTML:

<body>
    <form id="file_up_form" action="upload.php" method="post">
        <input type="file" id="fileToUpload" name="uploadedfile" />
        <!-- Click on submit to perform AJAX call -->
        <input type="submit" value="Upload"> 
    </form>
</body>

美元的ajaxform()行为(“# file_up_form”)。ajaxform({…})不触发一个Ajax请求。

它是一个事件绑定函数。(我没有经过API文档,但可能它将表单提交事件绑定到内部库函数之一)

实际上触发一个Ajax请求你添加<;输入type=“提交”>;里面的html & lt按钮;形式>;,并点击它。(图书馆将避免传统的表单提交,提交通过Ajax)

实例的实现:

JS:

<script type="text/javascript">
$(document).ready(function(){
    $("#file_up_form").ajaxForm({ // bind library function to the form
        beforeSend: function(xhr){
            input = document.getElementById('fileToUpload');;

            file = input.files[0];

            if(file){
                var reader = new FileReader();
                reader.readAsBinaryString(file);

                var shaObj = new jsSHA(reader.result,"BYTES");
                var hash = shaObj.getHash("SHA-512", "HEX");

                xhr.setRequestHeader('Sha-Sha', hash);
            }else{
                alert("First, please select a file to upload.");
                return false;
            }
        },
        uploadProgress: function(event, position, total, percentComplete){ },
        success: function() { },
        complete: function(response) { },
        error: function() { }
    });
});
</script>

HTML:

<body>
    <form id="file_up_form" action="upload.php" method="post">
        <input type="file" id="fileToUpload" name="uploadedfile" />
        <!-- Click on submit to perform AJAX call -->
        <input type="submit" value="Upload"> 
    </form>
</body>
answer2: 回答2:

Thx,

But that can't work because javascript is ***** not synchrone and I need to force the synchronisation with the reader.onload() callback and then call ajax ... the ajax request will be sent, no matter if the hash is computed or not, if I am inside .ajaxForm() it's over, even the setTimeout(function(){...}) is asynch itself too, so it has no effect the ajax request is sent ... or if I place it in an other place it just crash firefox ...

I have an upload button to trigger the request as you mention of course, and it is the only trigger I have to process the computation of the sha-512 first and then trigger ajax with the form binding.

But what I don't understand is :

why "startUp('ARandomHash');" works perfectly inside the $("#start_up_button").on('click', function() {...}); and "hash=...; console.log(hash); startUp(hash);" print the correct hash but ajax is a total fail inside the reader.onload() callback ... the event is trigger by the same click event, it has just 2 scope of execution more ...

I don't think I am loosing the submit event with these 2 scope more because the file is uploaded correctly ... it is just the beforeSend:..., uploadProgress:..., etc that are not executed.

I think I'll rather try to cast hash, it may be a character encoding problem, it has no sense otherwise, it should fail for the "startUp('ARandomHash');" as well ...

But thx, if someone has a better idea =)

谢谢,

但是,不能工作,因为JavaScript是*****不同步,我需要与读者同步的力量。onload()回调然后调用Ajax…Ajax请求将被发送,不管哈希计算或没有,如果我在里面。ajaxform()完了,连setTimeout(function() {…})是试验本身,所以它没有效果的Ajax请求发送…或者如果我把它放在另一个地方它只是崩溃Firefox…

我有一个上传按钮来触发请求你所说的那样,当然,它是唯一的触发我要过程的SHA-512先计算触发Ajax与形式的结合。

但我不明白的是:

为什么“启动('arandomhash ');“完美的作品在$(“# start_up_button”),(听到咔哒声,function() {…});和“哈希=…;控制台日志(哈希);启动(哈希);“打印正确的哈希但Ajax在读者总失败onload()回调…事件是由相同的单击事件触发的,它只有2的执行范围…

我不认为我失去了提交事件与这2个范围更因为文件上传正确…这仅仅是beforesend:…,uploadprogress:不执行,等。

我想我宁愿尝试投散列,它可能是一个字符编码的问题,它没有意义的话,它应该为“启动失败('arandomhash ');”为好…

But 谢谢, if someone has a better idea =)

javascript  ajax  file  upload  callback