call a ajax inside an xhr inside a for loop

I am trying to call an ajax inside a loop xhr request but the ajax results only yields me the last one..or just once..

$("#txtArea").contents().find('img').each(function () {
            ctr++;
            xhr= new XMLHttpRequest();
            xhr.open('GET', $(this).attr("src"), true);

            xhr.responseType = 'blob';

            xhr.onload = function (e) {
                if (this.status == 200) {
                    var blob = this.response;
                    var reader = new window.FileReader();
                    reader.readAsDataURL(blob); 
                    reader.onloadend = function() {
                        base64data = reader.result;


                        console.log("cheweee");

                    base64ToImage(base64data, ctr);  <<--this is the ajax call

                    }


                }

            };

here is the ajax

function base64ToImage(base64data,ctr) {

    $.ajax({
        method: "POST",
        url: "ConvertB64",
        async: false,
        data: {
            base64datastring: base64data, imgctr: ctr
        },
        success: function (data) {
            console.log(data);
        }
    })

        .done(function (msg) {
            console.log(msg);
        });
}

so what i'm trying to do is..I'm converting an object url to blob then pass that blob to be converted into image then i return the image location for my img tag.

on the xhr side I am able to get the blob data fine but the conversion to image happens only once. and its the last blob.

im using mvc. and I tried creating a arrayed xhr like this xhr[ctr] and I also added asynch: false.

thanks


I think the issue is your ctr variable is being shared by all renditions of the loop and is equal to the final value in that loop always. Try using the index passed into the .each() function instead:

$("#txtArea").contents().find('img').each(function (i) {
    ...
    ...
    base64ToImage(base64data, i+1); //index starts with 0 so adding 1
});

尝试使第一个Ajax请求同步,并检查.....因为你同时发送多个Ajax请求,响应没有排序,这可能是问题

链接地址: http://www.djcxy.com/p/51964.html

上一篇: 即使不匹配也会返回所有结果,并延迟ajax

下一篇: 在for循环中调用一个xhr内的ajax