Home > database >  How to get json data from url
How to get json data from url

Time:12-06

i have js code like this

var data = {
  "items": [
{
"src": "xxx",
"url": "xxx",
"ttl": "xxx%"
},
]};


$.each(data.items, function(i, f) {
  $('ul').append('<li ><a href="'   f.url   '"><img  src="'   f.src   '" download="'   f.ttl   '"></img></a></li>');
});

its work perfectly but i want replace var data ={xxx} with import url from github

i have try this code but not work :)

$.getJSON('https://raw.githubusercontent.com/user/lokal.json', data.items, function(i, f) {
  $('ul').append('<li ><a href="'   f.url   '"><img  src="'   f.src   '" download="'   f.ttl   '"></img></a></li>');
});

and this is my json

var data = {
  "items": [
{
"src": "https://xxx",
"url": "https://xxx",
"ttl": "METRO  TV"
}
]};

plzz help me

CodePudding user response:

this is for you reference. you need to loop through items from your json data. Demo https://jsbin.com/nicacux/edit?html,js,console,output

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    </head>
    <body>
        <ul></ul>
    </body>
</html>

JS

$(document).ready(function() {
    $.getJSON('https://jsonblob.com/api/1049293810068373504', data.items, function(i, f) {

        $.each(i.items, function(j, v) {
            console.log(v, f);
            $('ul').append('<li >'   v.ttl   '<a href="'   f.url   '"><img  src="'   f.src   '" download="'   f.ttl   '"></img></a></li>');
        });
    });

});

CodePudding user response:

You are using .getJSON incorrectly.

.getJSON will return data and you need to use that data to loop over and process.

Check this out: .getJSON

Following code should work for you:

$.getJSON('https://raw.githubusercontent.com/firzi15/stb21/main/lokal.json', function (data) {
  $.each(data.items, function(i, f) {
    $('ul').append('<li ><a href="'   f.url   '"><img  src="'   f.src   '" download="'   f.ttl   '"></img></a></li>');
  });
});
  • Related