Search code examples
jqueryjsonjson-server

Getting data from JSON-Server to local JQuery


Local HTML and JSON-Server data. Getting the data from JSON-Server and using it in JQuery.

Resolved with help of Kevin B and Sirko. Leaving the JS (JQuery) so it can be coppied in the future.

var i = 0;
var output;

$("#send").click(function(e) {
    $.getJSON("http://localhost:3000/db", function(data) {})
        .done(function(json) {
            $.each(json, function(key, val) {
                output+= '<p>name=' + json[i].name + '</p>';
                i++;
            });
            $("#paragraph").append(output);
        })
        .fail(function(jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        });

});

Solution

  • Consider the following.

    $(function() {
      $("#send").click(function(e) {
        console.log("Send clicked.");
        $.getJSON("./empleados", function(data) {
          console.log("Getting Items");
          var list = $("<ul/>", {
            class: "my-new-list"
          }).appendTo(".tablaemple");
          $.each(data, function(i, item) {
            var row = $("<tr>", {
              "data-nomina": item.nomina
            }).appendTo(list);
            $("<td>").html(item.nomina).appendTo(row);
            $("<td>").html(item.apellido + ", " + item.nombre).appendTo(row);
            $("<td>").html(item.base).appendTo(row);
            $("<td>").html(item.funcion).appendTo(row);
            $("<td>").html(item.flota).appendTo(row);
            $("<td>").html(item.tipoescalafon).appendTo(row);
          });
        });
      });
    });
    

    Your URL Path should be relative otherwise you might encounter a CORS issue.

    This will make a Row and then add Cells for each item in data.

    Please test this and post your results.