0

I am a python programmer, so am unsure how to do this in JavaScript.

Example input (from a REST service providing JSON):

[{"name": "foo", "id": 1024}, {"name": "bar", "id": 1025}]

Output:

<table>
    <thead>
            <tr><th>name</th> <th>id</th></tr>
    </thead>
    <tbody>
            <tr><td>foo</td> <td>1024</td></tr>
            <tr><td>bar</td> <td>1025</td></tr>
    </tbody>
</table>

Attempt (this is as far as I've gotten, trying just with the list example first from the JQuery docs, before trying to make it a table):

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <ul class="my-new-list"></ul>
        <script>
          $.getJSON('http://www.servicestack.net/ServiceStack.Northwind/customers?format=json', function(data) {
          var items = [];

          $.each(data, function(key, val) {
            items.push('<li id="' + key + '">' + val + '</li>');
          });

          $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
          }).appendTo('body');
        });
        </script>
    </body>
</html>

I'm sure it's just some n00bish mistake on my part, but unsure what it is. Could you please point it out?

Preferably I would like a python-like view with dictionary syntax (maybe Handlebars can provide this?), so that I can just go for person in this_list: <tr>person.name</tr>.

Musa
  • 96,336
  • 17
  • 118
  • 137
user1438003
  • 6,603
  • 8
  • 30
  • 36
  • Are you getting an error? Are you getting a response from the server? – anAgent Aug 01 '12 at 19:26
  • If you are using JSON between domains, you should look into and understand JSONP, here is a helpful blog post on it: http://www.jquery4u.com/json/jsonp-examples/#.UBmDjMie6z4 – Justin Jenkins Aug 01 '12 at 19:33
  • [in reply to deleted answer]: Yes, basically I would like it to generate a table with those field IDs dynamically found and set as table headers, and their values set per-record as table rows. This is likely a generic problem. – user1438003 Aug 01 '12 at 19:40
  • @anAgent: Getting a blank screen, nothing is happening. – user1438003 Aug 01 '12 at 19:40
  • @JustinJenkins: I'm confused at how to use that as replacement for the above, also unsure still how to make it into a nice table layout. – user1438003 Aug 01 '12 at 19:42

2 Answers2

1

First, your jQuery wouldn't even run since you never triggered it, or wrapped it in something like ...

$(document).ready(function() { ... });

See here: Introducing $(document).ready()

Second, you can't load JSON from another domain via Javascript unless you use JSONP, see: jQuery’s JSONP Explained with Examples. Typically you'll use PHP, .Net, Ruby whatever to load the JSON to your server and make it available for your script.

Example: Handling data in a PHP JSON Object

Lastly, javascript/jQuery will allow you to use a syntax like person.name it all depends on how your object or array is structured.

As for a 'nice' layout there are so many options I couldn't really begin to explain them here ... but it'll all be for not if you can't even load the data in the first place! :)

Here is a old but still useful tutorial explaining this: http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php

Community
  • 1
  • 1
Justin Jenkins
  • 26,590
  • 6
  • 68
  • 1,285
0

There are a couple of problems here. Justin Jenkins already mentioned the two most severe ones.

In addition to that also sure that the answer from the server is an array and not an object. Your current url responses with an object. So in that case, you have to access the array: $.each(data.Customers ... does the trick here.

Secondly the function called by iterating over the array gets a key and a value. But doesn't aren't the attributes of the object, but key is in this case 0...n (index of the array) and value is the object. So if you want to access the objects in the array, use val.property instead.

The code then might look something like this:

$.getJSON('http://www.servicestack.net/ServiceStack.Northwind/customers?format=json', function(data) {

var items = [];

$.each(data.Customers, function(key, val) {
  items.push('<li id="' + val.id + '">' + val.name + '</li>');
});

$('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

Of course assuming your request is successful.

Here's a jsfiddle which doesn't use the request, but shows you the use of the jquery iterate function.

http://jsfiddle.net/jomikr/zg2y5/

jokr
  • 242
  • 3
  • 13