开发者

jQuery getJSON Output using Python/Django

So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests. The address being used is:

http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296

I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).

Here's my simple attempt at just alerting/returning the data:

$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
    alert(json);
    <!--$.each(json.items, function(i,item){
    });-->
});

I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)

My views.py function that is generating this response looks as follows:

def tonight_mobile(request):
    callback = request.GET.get('callback=?', '')    

    def with_rank(rank, place):
        return (rank > 0)

    place_data = dict(
        Places = [make_mobile_place_dict(request, p)开发者_如何学C for p in Place.objects.all()]
    )

    xml_bytes = json.dumps(place_data)
    xml_bytes = callback + '(' + xml_bytes + ');'

    return HttpResponse(xml_bytes, mimetype="application/json")

With corresponding urls.py configuration:

(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),

I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies. Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL. Could someone assist me with some direction?


First, callback = request.GET.get('callback=?', '') won't get you the value of callback.

callback = request.GET.get( 'callback', None ) 

Works much better.

To debug this kind of thing. You might want to include print statements in your Django view function so you can see what's going on. For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜