简体   繁体   English

如何下载文本文件并以字符串形式存储在jQuery中

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

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. 我有一组文本文件,它们代表我想使用JavaScript应用程序下载的来自第三方的数据表。 They look something like this: 他们看起来像这样:

col1 col2 .. coln
vala valb .. valz
valA valB .. valZ
etc..

I've been trying to use jQuery to do this. 我一直在尝试使用jQuery来做到这一点。 I've been able to use $.load, but I don't want to store the data in the DOM, instead I'd like to parse it out into an object. 我已经可以使用$ .load,但是我不想将数据存储在DOM中,而是想将其解析为一个对象。 Whenever I try to use an of the ajaxy methods I'm getting an error I don't understand. 每当我尝试使用一种ajaxy方法时,都会收到我不理解的错误。 For example: 例如:

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

Gives me an undefined value for myData . 给我myData一个undefined值。 Any suggestions would be appreciated. 任何建议,将不胜感激。

For that code to work the event needs to be syncrounus, in other word, set async: false in the $.ajax-call. 为了使该代码正常工作,事件需要是同步的,换句话说,在$ .ajax调用中设置async:false。 The problem comes because ajax is normally async, meaning that when you do the alert, the request might, or might not have finished. 之所以会出现问题,是因为ajax通常是异步的,这意味着当您执行警报时,请求可能会或可能不会完成。 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. 因此,通过设置async:false,可以让jquery(和ajax处理程序)等待页面加载完成,然后再尝试警告数据。 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. 这种方法可能比将async设置为false更好,因为它不会在等待页面加载时使浏览器挂起。 However, asynchronous programming is not something that is easy to learn, therefore many will find it easier to use async: false. 但是,异步编程不是容易学习的东西,因此许多人会发现使用async:false会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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