简体   繁体   中英

Load txt file to div using JavaScript

Right now i have JavaScript functions working with this code but need help replacing the div with image links I have stored in a txt file so i dont want to alter the <div id="GALLERY"> just the data inside I have the links stored line by line in the txt file. also need help adding '<img src="' at the beginning and "> at the end for each line the pics.txt loads into the div

txt file is called pics.txt

<div id="GALLERY">
</div>

here is what the pics.txt looks like

http://www.clearviewarts.com/thumbnails/Pug.jpg
http://www.clearviewarts.com/thumbnails/BabyIndy.jpg
http://www.clearviewarts.com/thumbnails/CanusAngelicus.jpg
http://www.clearviewarts.com/thumbnails/Puppy%20In%20Basket.jpg
http://www.clearviewarts.com/thumbnails/Wagner-edit1.jpg
http://www.clearviewarts.com/thumbnails/HarlequinDane.jpg

Put these links in a file which in JSON format so that you can parse it easily.

Assuming that you have known AJAX. So load this file form server with AJAX.

Here is the code example with jQuery.

//urls.json is the file used to store those links
$.getJSON('urls.json', function(data) {
   //just Google how to parse JSON with javascript. It is quite easy 
   //Then you can put the links in an array
});

Here is the JSON file format

{
"links": [
"http://www.clearviewarts.com/thumbnails/Pug.jpg",
"http://www.clearviewarts.com/thumbnails/BabyIndy.jpg",
"and so on.."
]
}

PS Always use JSON or XML format for data communication. And JSON is much better.

If you can't load the picture file as JSON, you can try splitting it at the new line character:

$.get('pics.txt', function(data) {
  $.each(data.split('\n'), function(i, d) {
     $('#gallery').append('<img src="'+d+'"><br>');
  });
});

This will append every image url inside an image tag to the DIV with id gallery. You probably want to change the HTML to make it do or look like what you want.

NB: this assumes you're using jQuery

Edit: In it's simplest form, the entire HTML will look like this. This is how I tested the bit of code above, and got results. It assumes 'pics.txt' is in the same directory as the HTML file. Edit the location ( in $.get('pic/location/pics.txt' etc. It uses a jQuery version hosted by Google.

<html>
<head></head>
<body>

<div id="gallery"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.get('pix.txt', function(data) {
  $.each(data.split('\n'), function(i, d) {
        $('#gallery').append('<img src="'+d+'"><br>');
  });
});

</script>
</body>    
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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