Ajax Post in Django framework?

前端 未结 2 565
陌清茗
陌清茗 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!

    0 讨论(0)
  • 2021-02-06 15:15

    I can see the contents of the post in firebug's 'response' tab, but whether I try to return a template or a simple message, nothing happens in the browser itself. Conversely, a non-ajax post works as expected (loads new page, posts message)

    If you're getting a response, you're getting a response. You're just not doing anything with it.

    Why not alert the data and append it to the <body> for example:

    $.ajax({
         type:"POST",
         url:"/test_results/",
         data: {
                'arbitrary-data': 'this is arbitrary data',
                'some-form-field': $("myform input:first").val(), // from form
                'background-color': $("body").css("background-color")
                // all of this data is submitted via POST to your view.
                // in django, request.POST['background-color'] 
         },
         success: function(data){
             alert(data);
             $("body").append(data);
         }
    });
    
    0 讨论(0)
提交回复
热议问题