当前位置: 代码迷 >> JavaScript >> 使用javascript从txt文件读取文本,并在引导模式对话框中显示(通过组合键绑定)
  详细解决方案

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

热度:32   发布时间:2023-06-05 15:58:33.0

我正在尝试编写一个函数,该函数将从.txt文件(目前位于网站的根目录中)中读取数据,然后将其显示在模式对话框中。 我感觉我快要调试了,因为在调试模式时可以识别该文件,但是它什么也不显示:

HTML按钮:

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

Knockout.js虚拟机:

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

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)

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

Javascript选择文件名ok,但不返回任何文本,因此模式弹出窗口仅为空白。 有人可以帮忙解决我在哪里出错吗? 谢谢。

您应该使用可观察的

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

在html中,您应该调用它...

<div class="modal-body" id="logText">
    <span data-bind="text: observable"></span>
</div>
  相关解决方案