打印到html行和列是向后的(JSON CALL)

时间:2017-04-05 17:04:01

标签: python html json dictionary html-table

我在index.html中有以下代码,它抓取字典列表并将键和值打印到表中

$(function() {
  $('a#search').bind('click', function() {
    $.getJSON('/_search', {
      a: $('input[name="a"]').val()
    }, function(data) {
      var tableData = '<table>'
      $.each(data.result, function(key, value){
        tableData += '<tr><td>' + '   ' + key + '   ' + '</td>';
        alert(key)
        $.each(value, function(val){
            alert(value[val])
            tableData += '<td>' + value[val] + '</td>';
          });
        tableData += '</tr>';
      });
      tableData += '</table>';
      $('#table').html(tableData);
    });

它抓住的是来自search.py​​

的字典列表
result = defaultdict(list)
return jsonify(result=result)

结果包含以下内容

defaultdict(<class 'list'>, {'Developer': ['Office Koukan', 'Jorudan', 'Beam Software'], 'Publisher': ['Shouei', 'VAP', 'Hi Tech Expressions'], 'ReleaseDate': ['March 18, 1994', 'November 18, 1994', 'October 1, 1993'], 'Title': ['Idea no Hi', 'Pachinko Hi Hisshouhou', 'hunThe Hunt for Red October']})

但是我的输出如下

Developer Publisher ReleaseDate Title
Office    Koukan    Jorudan Beam Software
Shouei    VAP       Hi Tech Expressions
March 18, 1994  November 18, 1994   October 1, 1993
Idea no Hi  Pachinko Hi Hisshouhou  hunThe Hunt for Red October

当输出应为

Developer      Publisher ReleaseDate Title
Office         Shouei    ...         ...
Koukan         VAP       ...         ...
Jorudan        ...       ...         ...
Beam Software  ...       ...         ...

知道我可能做错了吗?

1 个答案:

答案 0 :(得分:0)

这是我所引用的一个示例(注意我拿出了获取数据并硬编码的部分,将结果推送到div。

请注意,简单数组的处理方式与使用$.each()的对象数组的方式不同,关于索引与关键对象名称(如您拥有的标题值)

//要使用的样本数据(而不是json调用)

var mything = {
  'Developer': ['Office Koukan', 'Jorudan', 'Beam Software'],
  'Publisher': ['Shouei', 'VAP', 'Hi Tech Expressions'],
  'ReleaseDate': ['March 18, 1994', 'November 18, 1994', 'October 1, 1993'],
  'Title': ['Idea no Hi', 'Pachinko Hi Hisshouhou', 'hunThe Hunt for Red October']
};

$(function() {
  var data = mything;// sample data
  // create a table to append rows to
  var tableData = $('<table>');
  // append a header row
  tableData.append('<tr/>');
  // reference that header row to append header td to
  var header = tableData.find('tr').eq(0);
  $.each(data, function(headthing, value) {
    header.append('<td>' + headthing + '</td>');
    $.each(value, function(idx, myval) {
      if (!tableData.find('tr').eq(idx + 1).length) {
        tableData.append('<tr/>'); // new row if not one
      }
      // put the columns in the row for each data
      tableData.find('tr').eq(idx + 1).append('<td>' + myval + '</td>');
    });
  });
  // put the table somewhere
  $('#results').html(tableData);
});

这是一个显示它的小提琴https://jsfiddle.net/MarkSchultheiss/ro5egfu3/1/