0

I have a basic log file like below:

Admin Login at 3:00
User A Login at 3:10
User B Login at 3:12
User M Login at 3:17
User D Login at 3:30
User E Login at 3:42
Admin Login at 4:00
User A Login at 4:03
User F Login at 4:15
.....

and I am using this jQuery Ajax call to list the logins:

<div >
    <ul id="result">

    </ul>
</div>
<script>
$.ajax({
    url: "data.txt",
    type: 'POST',
    dataType: 'text',
    success: function (data) {
       $('#result').append('<li>'+data+'</li>');
    },
    async: false
});
</script>

but (as expected!) I am loading all of the text file to only one <li> and the result look like:

. Admin Login at 3:00 User A Login at 3:10 User B Login at 3:12 User M Login at 3:17 User D Login at 3:30 User E Login at 3:42 Admin Login at > 4:00 User A Login at 4:03 User F Login at 4:15

How can I load each row of the text file into one separate <li>?

3
  • What is the format of data, is it a list or is it just one big string? Commented Nov 19, 2014 at 15:52
  • Your newlines are being ignored. Someone had a similar issue here: stackoverflow.com/questions/9726970/… Commented Nov 19, 2014 at 15:57
  • @jwang brings up a good point, Did you want the full text inside the <li> tag? like a <pre> tag that preserves new lines? or an <li> tag per each line of text? Commented Nov 19, 2014 at 15:59

1 Answer 1

3

Split the data by line separators:

$.each(data.split(/[\n\r]+/), function(index, line) {
  $('<li>').text(line).appendTo('#result');
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Sukirma, this is exactly what I want
Also note that the $.ajax method returns a jQuery deferred object so the need to deep indent a success property as a call back is antiquated and less flexible. See .then() for details
sure but I have to wait for 10 min to accept the answer as correct answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.