Kevin Kevin -4 years ago 63
HTML Question

How to Retrieve Images Using jQuery

I have this piece of code, and I was wondering how to get my images to load on my site using jQuery.

$.getJSON('https://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) {
const text = json.parse.text['*'];
const regex = /([-\w+\.\/]+(?:png|svg))/gmi;
let m;
while ((m = regex.exec(text)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
picture = regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
console.log(`Found match: ${m[1]}`);
}});


The images load on my console, but they won't load on my actual page. What can I do to display the images on my HTML page? Is that "m" variable what I need to use? I was told that my images would load on an absolute path, but I assume that these images are on a relative path, given it's coming from the Wikipedia API.

Answer Source

Using jQuery, just append an img element to an element on the DOM:

$.getJSON('https://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
  const text = json.parse.text['*'];
  const regex = /([-\w+\.\/]+(?:png|svg))/gmi;
  let m;
  while ((m = regex.exec(text)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
        picture = regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    $('#images').append('<img src="'+m[0]+'" />');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="images"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download