Datatables Ajax works when reading JSON from file,

2019-07-14 06:52发布

问题:

I've been stuck with this problem for a few days now. I'm trying to feed JSON data to DataTables, but it only works if I use static file as source (see below index.html).

index.html

$(document).ready(function() {
    $('#mydata').DataTable( {

          "ajax": {
            "url": '{% static "myapp/supplier.json" %}',  //<= works
{#                    "url": '{{ suppliers_all }}',#}     //<=does not work
            "dataSrc": ""
          },
            "columns": [
                { "data": "name" },
                { "data": "classification" },
            ]
    } );
} );

views.py

def index(request):
    suppliers_all = Supplier.objects.all().values('name', 'classification')
    suppliers_all = json.dumps(list(suppliers_all))
    context = {'suppliers_all': suppliers_all,
               }
    return render(request, 'myapp/index.html', context)

JSON output:

[{"classification": "Base Supplier", "name": "Supplier Name1"}, {"classification": "Strategic Supplier", "name": "Supplier Name2"}]

When I use django passed variable {{ suppliers_all }} browser debugging returns a 404 not found error. I tried hardcoding JSON output according to websites examples, tried many different ways, but it will never work if it's not fetched directly from file.

Update: Solved problem by creating new view with JSON Httpresponse and url

def supjson(request):
    suppliers_all = Supplier.objects.all().values('name', 'classification')
    suppliers_all = json.dumps(list(suppliers_all), cls=DjangoJSONEncoder)
    context = {'suppliers_all': suppliers_all,
    return HttpResponse(suppliers_all, content_type='application/json')

Then changed Ajax url to the following:

                  "ajax": {
                    "url": '{% url 'myapp:supjson' %}',
                    "dataSrc": ""
                  },

While it works, I feel it's redundant solution as I have issues passing data through the variable directly.

Update #2: Issue was due to Django autoescaping single commas which then made JSON parsing did not work. I did the following changes:

Added mark_safe in the views.py

context = {'suppliers_all': mark_safe(suppliers_all),
           }

Stringified JSON and then Parsed it in index.html template:

$(document).ready(function() {
var json=JSON.stringify({{ suppliers_all }});
    $('#mydata').DataTable( {
          "data": JSON.parse(json),

回答1:

Perhaps you don't need to load data from url. If your data is preloaded then try to add it directly to DataTable.

$(document).ready(function(){
    $('#mydata').DataTable({
        "data": JSON.parse('{{ suppliers_all }}'),
        "columns": [
            {"data": "name"},
            {"data": "classification"},
        ]
    });
});