简体   繁体   中英

jquery.get(url) synchronization

OS X 10.6.8, Chrome 15.0.874.121

I'm experiencing an issue with javascript/jquery: I want to download a header file from base url, then add some more text to it and than spit it out to the client. I'm using the following code:

var bb = new window.WebKitBlobBuilder;
$.get('js/header.txt', function(data) {
   bb.append(data);
   console.log("finished reading file");
});
console.log("just before getting the blog");
var blob = bb.getBlob('text/plain');
// append some more 
saveAs(blob,"name.dxf");

But that fails because getting the file is only finished way after the saveAs(blob) is executed. I know I can fix it with:

var bb = new window.WebKitBlobBuilder;
$.get('js/header.txt', function(data) {
   bb.append(data);
   //append some more
   var blob = bb.getBlob('text/plain');
   saveAs(blob,"name.dxf");
});

But that does not really look attractive: I only want to use the get statement only to append the header to the blob, and if I want to read a footer from the file system, I have to do a get inside a get , and spit out the blob in the inner get

Are there alternative ways to withhold the code after the get statement from executing until the whole file has been successfully loaded?

No.*

But, if you want it to look more attractive, try to describe semantically what you are trying to achieve and then write functions accordingly. Maybe:

function loadBlob (loadHeader, loadBody) {
    loadHeader(loadBody);
}
loadBlob(function (oncomplete) {
    $.get("js/header.txt", function(data) {
        bb.append(data);
        oncomplete();
    });
}, function () {
    var blob = bb.getBlob('text/plain');
    // append some more
    saveAs(blob,"name.dxf");
});

I don't know, is that more attractive? Personally, I find the original just fine, so maybe mine isn't any better, but the point is to use sematics.

* You could use setTimeout to poll and see if the response has been received. That's technically an alternative, but certainly not more attractive, is it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM