Ajax Post in Django framework?

前端 未结 2 564
陌清茗
陌清茗 2021-02-06 14:30

I put together a simple test of an ajax/jquery post within a django framework, but don\'t really understand why the output doesn\'t make it to a template page. Anyone?

I

2条回答
  •  有刺的猬
    2021-02-06 15:09

    You need to add a handler for the response returned by the view:

    $.ajax({
        type:"POST",
        url:"/test_results/",
        dataType: "json",
        success: function(json)
        {
            //specifying a dataType of json makes jQuery pre-eval the response for us
            console.log(json.message);
        }
     });
    

    You'll probably also want to encode the response as JavaScript in your view:

    try:
        import json
    except ImportError:
        import simplejson
    
    def my_view(request):
        if request.is_ajax():
            return HttpResponse(json.dumps({'message' : 'awesome'},
                ensure_ascii=False), mimetype='application/javascript')
    

    Hope that helps you out!

提交回复
热议问题