How to download a text file and store as a string in jQuery

前端 未结 1 695
名媛妹妹
名媛妹妹 2021-01-16 22:05

I have a set of text files representing a table of data from a third party that I\'d like to download using a JavaScript application. They look something like this:

1条回答
  •  有刺的猬
    2021-01-16 22:21

    For that code to work the event needs to be syncrounus, in other word, set async: false in the $.ajax-call. The problem comes because ajax is normally async, meaning that when you do the alert, the request might, or might not have finished. Normally though, it won't cause it takes longer time to fetch a page than to do a function-call. So, by setting async: false, you tell jquery (and the ajax-handler) to wait till the page is finished loaded before you try to alert the data. Another method to achieve the same effect is to do something like this:

    var myData;
    function fin(data) {
        myData = data;
        alert(myData);
    }
    $.ajax({
        type: 'GET',
        url: $(this).attr('source'),
        dataType: 'html',
        success: fin
    });
    

    This approach is probably better than to set async to false, because it won't make the browser hang while waiting for the page your loading. However, asynchronous programming is not something that is easy to learn, therefore many will find it easier to use async: false.

    0 讨论(0)
提交回复
热议问题