简体   繁体   English

使用javascript从txt文件读取文本,并在引导模式对话框中显示(通过组合键绑定)

[英]Read text from a txt file using javascript and display in a bootstrap modal dialog (via knockout binding)

I'm trying to write a function which will read data from a .txt file (which for the moment, is residing in the root directory of website) and then display it in a modal dialog box. 我正在尝试编写一个函数,该函数将从.txt文件(目前位于网站的根目录中)中读取数据,然后将其显示在模式对话框中。 I feel like I'm almost there as the file is being recognised when I debug the the modal, but it doesn't display anything: 我感觉我快要调试了,因为在调试模式时可以识别该文件,但是它什么也不显示:

HTML Button: HTML按钮:

<button class="btn btn-mini btn-success" 
        data-toggle="modal" 
        data-target="#openLog" 
        data-bind="click: GetLog">
        Start
</button>

Knockout.js vm: Knockout.js虚拟机:

GetLog = function () {
    dataServices.getLog();
}

HTML Modal: HTML模态:

<div class="modal fade" id="openLog" tabindex="-1" role="dialog" aria-labelledby="openLogLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="openLogLabel">Today's Log</h4>
            </div>
            <div class="modal-body" id="logText">
                <script>
                    window.onload = function () {
                        dataServices.getLog();
                    }
                </script>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Javascript (dataServices.js) Javascript(dataServices.js)

getLog = function() {
    return $.ajax({
        url: 'Text.txt',
        dataType: 'text',
        success: function (text) {
            getLog.logContents = text;
            $("#logText").text(text);
        }
    })
};

The Javascript picks up the filename ok, but returns no text so the modal popup is just blank. Javascript选择文件名ok,但不返回任何文本,因此模式弹出窗口仅为空白。 Can anyone please assist regarding where I'm going wrong with this? 有人可以帮忙解决我在哪里出错吗? thanks. 谢谢。

You should use an observable 您应该使用可观察的

var vm = {
  observable: ko.observable(''),
  getLog: function() {
      var self = this;
      return $.ajax({
          url: 'Text.txt',
          dataType: 'text',
          success: function (text) {
              self.observable(text);
          }
      })
  }
};
ko.applyBindings(vm);
vm.getLog();

And in the html you should call it... 在html中,您应该调用它...

<div class="modal-body" id="logText">
    <span data-bind="text: observable"></span>
</div>

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

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