如何下载一个文本文件,并存储为一个字符串的jQuery字符串、文本文件、如何下载、jQuery

2023-09-11 00:39:05 作者:冷顏い

我有一组文本文件重新$ P $的,我想用一个JavaScript应用程序下载第三方psenting数据表。他们看起来是这样的:

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:

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

我一直在尝试使用jQuery来做到这一点。我已经能够使用$ .load,但我不希望将数据存储在DOM中,而不是我想解析出来到一个对象。每当我尝试使用的ajaxy方法,我发现了一个错误,我不明白。例如:

I've been trying to use jQuery to do this. 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. Whenever I try to use an of the ajaxy methods I'm getting an error I don't understand. For example:

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

让我有的myData 未定义值。任何建议将是AP preciated。

Gives me an undefined value for myData. Any suggestions would be appreciated.

推荐答案

对于code工作时需要有syncrounus,换句话说,设置异步:假的$就调用。问题就来了,因为AJAX一般是异步的,这意味着当你做报警,请求可能会或可能不会完成。通常虽然,它不会导致它需要更长的时间来获取一个网页比做一个函数调用。因此,通过设置异步:假的,你告诉jQuery的(和AJAX的处理程序)要等到页面完成加载,然后再尝试提醒数据。要达到同样的效果另一种方法是做这样的事情:

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
});

这种方法可能会更好,而不是异步设置为false,因为它不会使浏览器挂起并等待页面加载的。然而,异步编程是不是一件很容易掌握,因此,很多人会发现它更容易使用异步:假的。

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.