html5多个xmlhttp请求更多响应

html5 multiple xmlhttprequest more response

本文关键字:响应 请求 多个 xmlhttp html5      更新时间:2023-09-26

大家好

我的HTML5XMLHttprequest上传程序有一个小问题。

我使用Filereader类从多个文件输入中读取文件,然后一次上传一个作为二进制字符串。在服务器上,我捕捉输入流上的比特,将其放在tmp文件中,等等。这部分很好。程序正常终止,发送响应,我在标题中看到了这一点(例如FireBug)。但是使用JS,我只捕获'onreadystatechange'中的最后一个。

我看不出所有人都有反应。为什么?如果有人能解决这个问题,那就太好了:)

你会看到相同的jQuery和Template,别担心:D

这是JS:

function handleFileSelect(evt)
{
    var files = evt.target.files; // FileList object
    var todo = {
            progress:function(p){
                $("div#up_curr_state").width(p+"%");
                },
            success:function(r,i){
                $("#img"+i).attr("src",r);
                $("div#upload_state").remove();
                },
            error:function(e){
                alert("error:'n"+e);
                }
        };

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
        // Only process image files.
        if (!f.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        var row = $('ul#image_list li').length;
            row = row+i;
        // Closure to capture the file information.
        reader.onload = (function(theFile,s) {
            return function(e) {
            // Render thumbnail.
            $("span#prod_img_nopic").hide();
            $("div#prod_imgs").show();
            var li = document.createElement('li');
            li.className = "order_"+s+" active";
            li.innerHTML = ['<img class="thumb" id="img'+s+'" src="', e.target.result,
                                '" title="', escape(theFile.name), '"/><div id="upload_state"><div id="up_curr_state"></div>Status</div>'].join('');
            document.getElementById('image_list').insertBefore(li, null);
            };
        })(f,row);
        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
        //upload the data
        //@param object fileInputId     input file id
        //@param int    fileIndex       index of fileInputId
        //@param string URL             url for xhr event
        //@param object todo            functions of progress, success xhr, error xhr
        //@param string method          method of xhr event-def: 'POST'
        var url = '{/literal}{$Conf.req_admin}{$SERVER_NAME}/{$ROOT_FILE}?mode={$_GET.mode}&action={$_GET.action}&addnew=product&imageupload={literal}'+f.type;
        upload(f, row, url, todo);
}

上传功能:

function upload(file, fileIndex, Url, todo, method)
 {
        if (!method) {
            var method = 'POST';
        }
        // take the file from the input
        var reader = new FileReader();
        reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
        reader.onloadend  = function(evt)
        {
                // create XHR instance
                xhr = new XMLHttpRequest();
                // send the file through POST
                xhr.open(method, Url, true);
                // make sure we have the sendAsBinary method on all browsers
                XMLHttpRequest.prototype.mySendAsBinary = function(text){
                    var data = new ArrayBuffer(text.length);
                    var ui8a = new Uint8Array(data, 0);
                    for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
                    var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)(); 
                    bb.append(data);
                    var blob = bb.getBlob();
                    this.send(blob);
                }
                // let's track upload progress
                var eventSource = xhr.upload || xhr;
                eventSource.addEventListener("progress", function(e) {
                    // get percentage of how much of the current file has been sent
                    var position = e.position || e.loaded;
                    var total = e.totalSize || e.total;
                    var percentage = Math.round((position/total)*100);
                    // here you should write your own code how you wish to proces this
                    todo.progress(percentage);        
                });
                // state change observer - we need to know when and if the file was successfully uploaded
                xhr.onreadystatechange = function()
                {  
                        if(xhr.status == 200 && xhr.readyState == 4)
                        {                                
                            // process success                               
                            resp=xhr.responseText;
                            todo.success(resp,fileIndex);
                        }else{
                            // process error
                            todo.error(resp);
                        }                            
                };
                // start sending
                xhr.mySendAsBinary(evt.target.result);
        };
   }
    }
}

和启动器事件

document.getElementById('files').addEventListener('change', handleFileSelect, false);

这是一个很小的错误:您忘记添加var语句:

    // create XHR instance
    var xhr = new XMLHttpRequest();
//  ^^^ add this

使用像您的一样的readystatechange处理程序功能

function() {  
    if (xhr.status == 200 && xhr.readyState == 4) {       
        resp=xhr.responseText; // also a missing variable declaration, btw
        todo.success(resp,fileIndex);
    } else {
        todo.error(resp);
    }                            
}

当任何请求触发事件时,仅检查了最新的xhr实例的statusreadyState。因此,只有当最后一个xhr触发事件本身时,才会执行成功函数。

解决方案:修复所有变量声明,我想这不是唯一一个(尽管会严重影响行为)。您还可以使用this而不是xhr作为对事件处理程序中当前XMLHttpRequest实例的引用。