javascript 如何使用 jQuery 将文件作为文本字符串加载到某个 var 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7910047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:41:02  来源:igfitidea点击:

How to load a file as a text string into some var with jQuery?

javascriptjqueryhtmlajax

提问by Rella

So we have a /page.htmland /folder/file.bla. We want to load that file contents as text string into some var using jQuery and call some function when we are done loading. How to do such thing?

所以我们有一个/page.html/folder/file.bla。我们想使用 jQuery 将该文件内容作为文本字符串加载到某个 var 中,并在加载完成后调用一些函数。这样的事情怎么办?

回答by David Bélanger

Get the file using $.AJAX :

使用 $.AJAX 获取文件:

$.ajax({
    type: 'GET',
    url: '/mypage.html',
    success: function (file_html) {
        // success
        alert('success : ' + file_html);
    }
});

回答by Clive

$.get('/folder/file.bla', function(data) {
  var fileContents = data;
});

The function you pass as the second argument to the get()functionwill be run once the data has been loaded from the external URL.

从外部 URL 加载数据后,您作为第二个参数传递给get()函数的函数将运行。

回答by Marco Johannesen

What type is the file? If its pure text, it shouldn't be a problem :)

文件是什么类型?如果是纯文本,应该不成问题:)

   $.get('/folder/file.bla', function(data) {
    var filetxt = data;
    // FINISHED GETTING FILE, INSERT CODE
    });