views:

390

answers:

2

I'm trying to generate a jqgrid which populates from a JSON feed, being output from a django backend.

The python handling the request is as follows:

from django.http import HttpResponse
from django.utils import simplejson
def json_test(request):
    results = {'total':'1',
               'page':'1',
               'records':'2',
               'rows':[{'id':'1','field1':'blah','field2':'bleh'},
            {'id':'2','field1':'bloo','field2':'blum'}]}
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/json')

So going to http://127.0.0.1:8000/json_test/ returns the following:

{"records": "2", "total": "1", "rows": [{"field2": "bleh", "field1": "blah", "id": "1"}, {"field2": "blum", "field1": "bloo", "id": "2"}], "page": "1"}

The jquery code is as follows:

<script type="text/javascript">
jQuery(document).ready(function(){ 
  jQuery("#list").jqGrid({
    url:'http://127.0.0.1:8000/json_test/',
    datatype: 'json',
    mtype: 'GET',
    colNames:['field1','field2'],
    colModel :[ 
      {name:'field1', width:55}, 
      {name:'field2', width:90}, 

    ],
    pager: '#pager',
    rowNum:10,
    rowList:[10,20],
    sortname: 'field1',
    sortorder: 'desc',
    viewrecords: true,
    caption: 'Test Grid'
  }); 
}); 
</script>

On loading the page, the grid renders correctly, and it briefly displays 'loading data', but it then displays no rows.

Any ideas where I've gone wrong? I've tried to strip this back to as simple a case as possible to determine the cause.

+1  A: 

According to the jqGrid Documentation, by default the grid expects JSON data in the following format:


{ 
  total: "xxx", 
  page: "yyy", 
  records: "zzz",
  rows : [
    {id:"1", cell:["cell11", "cell12", "cell13"]},
    {id:"2", cell:["cell21", "cell22", "cell23"]},
      ...
  ]
}

So basically it looks like you need to set an ID for each of your columns. If this is not feasible you would need to specify your own jsonReader.

Additionally, having your total/page/records sections out-of-order might cause problems - if you still have trouble after adding the ID's then this would be the next thing to look at.

Justin Ethier
I've added in the ids (code edited to reflect this) and still no joy. How can I force python to return the JSON in the coded order?
meepmeep
That was just an observation, I am not sure if it will cause problems or not. As a quick test, just return a hardcoded string in the right order and see if that fixes the problem. Then a solution can be worked out.
Justin Ethier
A: 

Solved - I put the html page inside the django app, so that the jqgrid url became just url:'/json_test/' and then it worked. Must be something harcoded into jqgrid that only permits local urls?

meepmeep