-2

我正在使用 Ajax get 调用 API 来收集 txt 格式的日志并将它们打印在网页上。我只想打印包含特定字符串 (USER_LOG) 的行,如果可能的话,只打印 USER_LOG 之后的所有内容,而在它之前没有任何内容。

这就是我用来在页面上打印日志的方法。

  $.ajax({
      url: "https://Path/to/API/log",
      headers: {
        "Authorization": "Auth"
      },
      method: 'GET',
      contentType: 'text/plain',
      success: function(data){
            $("#logs").html(data);
        $('#logs').animate({scrollTop: $('#logs')[0].scrollHeight}, 2000);
      },
      error: function (error) {
        clearInterval(interval);
        $("#button").prop("disabled", true);
      }
    });

我认为这样的事情会奏效,但我没有任何运气。我对 JavaScript 很陌生,所以任何帮助都将不胜感激。

$.ajax({
      url: "https://Path/to/API/log",
      headers: {
        "Authorization": "Auth"
      },
      method: 'GET',
      contentType: 'text/plain',
      success: function(data){
      var lines = data.split("\n");
        for (var i = 0; i < lines.length; i++) 
         {
          if (lines.indexOf("USER_LOG") != -1) 
          {
            $("#logs").html(lines);
          }
        }
      },
      error: function (error) {
        clearInterval(interval);
        $("#button").prop("disabled", true);
      }
    });
4

1 回答 1

-2

尝试这个:

//I added this array to simulate the API response
var data = "line 1 USER_LOG TEXT TO PRINT \n line 2 USER_LOG TEXT TO PRINT 2";

var lines = data.split("\n");
  for (var i = 0; i < lines.length; i++)
  {
    var line = lines[i]; //extract the single line, in your snipet you were trying to print the whole array
   {
    if (line.indexOf("USER_LOG") != -1) 
    {
      //get only the text after 'USER_LOG' for the single line
      var textToPrint = line.split('USER_LOG')[1];
      //instead of replacing the html with .html() use append()
      $("#logList").append("<li>"+textToPrint+"</li>");
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="logs">
<ul id="logList"></ul>
</div>

于 2019-09-16T21:37:03.333 回答