javascript 使用 jquery 从服务器上的文本文件读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6269159/
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-25 20:05:41  来源:igfitidea点击:

Read from textfile on server using jquery

javascriptjquerytext

提问by prometheuspk

I have a textfile (.txt) on a server. It contains only one word i.e. ON or OFF. How can i use JQuery or Pure Javascript to read that word from the file.

我在服务器上有一个文本文件 (.txt)。它只包含一个词,即 ON 或 OFF。我如何使用 JQuery 或 Pure Javascript 从文件中读取该单词。

I am thinking along the lines of $.ajax.

我在思考 $.ajax.

回答by Darin Dimitrov

You could use the $.getmethod to send a GET AJAX request to a resource located on the server:

您可以使用该$.get方法向位于服务器上的资源发送 GET AJAX 请求:

$.get('/foo.txt', function(result) {
    if (result == 'ON') {
        alert('ON');
    } else if (result == 'OFF') {
        alert('OFF');
    } else {
        alert(result);
    }
});

回答by Fosco

You can use $.getto grab the content of that file, and then take action based on the data returned:

您可以使用$.get获取该文件的内容,然后根据返回的数据采取行动:

$.get('/path/to/file.txt',function(data) {
   if (data == "ON") {

   } else {

   }
});

回答by Tomasz Dzi?cielewski

You can also use this file as a config (for future development) and keep there more informations, for example:

您还可以将此文件用作配置(用于未来开发)并保留更多信息,例如:

yourfile.txt:

你的文件.txt:

{"enable":"ON","version":"1.0"}

and additionally use JSONto parse file content:

并另外用于JSON解析文件内容:

$.get('/path/yourfile.txt', function(data) {
    var config = JSON.parse(data);
    if(config.enable == 'ON') {
         // ...
    } // ...
    if(config.version == '1.0') {
         // ...
    } // ...
});