Domanda

Thanks for taking the time to look at my question.

I am building a hybrid app with Sammy.js on the front-end and Django on the back. My site is just a single index.html hosted on S3 via CloudFront, and no, it's not homework :)

I would like to render a list of categories for the route "#/projects", with the categories coming from a JSONP request to my django backend, running on a different domain.

My Django view:

def get_categories(request):
    jsoncallback = request.GET.get('jsoncallback')
    data = {'categories': [{'name': c.name, 'slug': c.slug} for c in categories]}
    jsonp = '{0}({1});'.format(jsoncallback, data)
    response = json.dumps(jsonp, ensure_ascii=False)
    return HttpResponse(response, content_type='application/json')

My Sammy route:

(function($) {
    var app = $.sammy('#app', function() {

    // (default route here)

    this.get('#/projects', function(context) {
        // localhost via manage.py runserver
        $.getJSON('http://localhost:8000/projects/categories/?jsoncallback=?',
            null, function(categories) {
                $.each(categories, function(i, category) {
                    console.log('here');
                    // code to render template here
                });
        });
    });

    $(function() {
        app.run('#/');
    });
})(jQuery);

The response portion of call to my Django view in Firebug is:

"jQuery183018328394494212097_1372132674985({'categories':
    [{'name': u'Open Source', 'slug': u'open-source'},
     {'name': u'Web Development', 'slug': u'web-development'},
     {'name': u'Print', 'slug': u'print'}]});"

However, my console.log statement is never reached. I'm not sure what I'm doing wrong. Can someone please point me in the right direction? Several hours of tinkering and following the many JSONP examples on the web is, unfortunately, not helping.

È stato utile?

Soluzione

Turns out this was a simple problem to fix. I was simply mis-using json.dumps(). This was the correct way to form my response:

def get_categories(request):
    jsoncallback = request.GET.get('jsoncallback')
    data = {'categories': [{'name': c.name, 'slug': c.slug} for c in categories]}
    json_data = json.dumps(data, ensure_ascii=False)
    response = '{0}({1});'.format(jsoncallback, json_data)
    return HttpResponse(response, content_type='application/json')

The tell-tale sign in the response I was getting previously was that it was a string instead of JSON (notice the quotes around the function).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top