Display Data From Text File With Jquery
I need to display/append the data from a file, file.txt, containing 400 lines which are in the following format: http://www.exemple.com/img1.jpg, title1, subtitle1, description1;
Solution 1:
You could split
a second time:
$.each(lines, function(n, line) {
// Breaks up each line into ['src', 'title', 'subtitle', 'description']
var elements = line.split(', ');
$('#display').append('<div><img src="' + elements[0] + '"/></div>');
});
Solution 2:
You can split on the ' '
:
$.get('file.txt', function(data) {
//var fileDom = $(data);var lines = data.split("\n");
$.each(lines, function(line, elem) {
var parts = line.split(', '), // this splits the line into pieces
src = parts[0],
title = parts[1],
subtitle = parts[2],
description = parts[3].slice(0, -1); // remove the ';' from the description// at this point, you have the pieces of your line and can do whatever// you want with the data
$('#display').append('<div><img src="' + src + '"/></div>');
});
});
Solution 3:
Your error resides on the way you split...
You need to do something like that, (.when(file)
should be replaced with .get('file.txt')
:
var file = "http://www.exemple.com/img1.jpg, title1, subtitle1, description1; http://www.exemple.com/img2.jpg, title2, subtitle2, description2; http://www.exemple.com/img3.jpg, title3, subtitle3, description3; http://www.exemple.com/img4.jpg, title4, subtitle4, description4; http://www.exemple.com/img5.jpg, title5, subtitle5, description5;";
functionAppendImagesCtrl($) {
$
// .get('file.txt')
.when(file) // this is a fake
.then(file => file.split(/; ?\n? ?/))
.then(lines => lines.map((line, i) => {
line = line.trim();
if(!line) { return""; }
let [
img, title, subtitle, description
] = line.split(/, ?n? ?/);
return`<article id="${(i + 1)}">
<h1>${title}</h1>
<img src="${img}" alt="${img}" />
</article>`;
}))
.then(view => $('#example').append(view))
;
}
window.jQuery(document).ready(AppendImagesCtrl);
img { width: 100px; height: 50px; background: cyan; }
article { padding: 5px10px; background: lightseagreen; margin-bottom: 5px;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="example"></div>
Post a Comment for "Display Data From Text File With Jquery"