开发者

Django/AJAX/JQuery - Simple POST troubles

开发者 https://www.devze.com 2023-03-20 16:11 出处:网络
I\'m trying to implement the simplest AJAX POST I can think of because I\'m new to AJAX and JQuery. The idea is this: I have a button, and when it is clicked I want to submit basic POST data to the sa

I'm trying to implement the simplest AJAX POST I can think of because I'm new to AJAX and JQuery. The idea is this: I have a button, and when it is clicked I want to submit basic POST data to the same page (the page is: http://{{ my ip address }}/django/ajax/ ).

In my .html file I have:

<script type="text/javascript">
    function pythonizer(){
        $("#msgid").append("it SHOULD post after this is appended");
        $.ajax({ 
        url: '/django/ajax/', 
        type: 'POST', 
        data: {'obj': "test string"}, 
        dataType: 'json', 
        contentType: "application/json; charset=utf-8",
        success: function(response) {
                   alert(response);
            }
        }); 
        }
</script>    

<div id="msgid">
</div>

<input type="button" id="myButton" value="click me" onclick="pythonizer()" />

And my relevant function in view.py is:

def ajax(request):
    if request.method == 'POST':
        return HttpResponse("Hello AJAX")   

    return render_to_response('huh.html', {})

Simple, right? The problem however, is that when I click my button, the "it SHOULD post after this is appended" is successfully added to the div, but nothing else happens, HttpResponse("Hello AJAX") is not returned, the POST isn't working!

What I've written seems consistent with the documentation I've read, but I have a feeling I'm either missing something stupid, or trying to oversimplify the POST. Thanks in advan开发者_如何学Cce!


I don't know django or python, but the problem with your javascript is that it's not doing anything when the AJAX call completes.

<script type="text/javascript">
function pythonizer(){
    $("#msgid").append("it SHOULD post after this is appended");
    $.ajax({ 
    url: '/django/ajax/', 
    type: 'POST', 
    data: {'obj':data},   // <-- possible error?
    dataType: 'json', 
    contentType: "application/json; charset=utf-8",  
    success: function (response) {
        alert(response);
    }
    }); 
    }
</script>

This will alert whatever you write to the response (presumably "Hello AJAX").

Also, there's an error in your script: you haven't defined 'data' (as in data: {'obj':data},). this script won't execute as-is, unless you declared data elsewhere.


May be error in here?

    success: function(response) 

I can't tell you more without the debug info... Is python receiving request at all? Maybe it's a problem that it rejects CSRF validation and you need to add and import it:

@csrf_exempt
def myview(request):
    print 'hello'

perhaps you could read more about it here: https://docs.djangoproject.com/en/1.2/releases/1.2.5/#csrf-exception-for-ajax-requests

Maybe its better not to go so deep at first IMHO?

So why don't you use another jQuery shortcut?

$.post('/django/ajax/', data, function(data){
                                 alert(data);
                              });

Maybe I'm mistaken with your personal code, but I think you'll simply figure it out with it's official help here: http://api.jquery.com/jQuery.post/

There are two good things for this:

  1. Firebug (Mozilla firefox and maybe some other browsers are good too)
  2. Django Debug toolbar

They are good for debugging in both python and jQuery sides... Try to learn to use them... (if you don't already and I'm sorry to tell you such a obvious thing in that case :) )


I'm assuming you want a JSON response.

The jquery document explains the different dataTypes that can be used. When dataType:'json' is used the ajax method is expecting the response context-type to be in JSON.

In the template html file try this:

<script type="text/javascript">
function pythonizer(){
    var data = "data";
    $("#msgid").append("it SHOULD post after this is appended");
    $.ajax({ 
        url: '/django/ajax/', 
        type: 'POST', 
        data: {obj:data},
        dataType: 'json', 
        contentType: "application/json; charset=utf-8",  
        success: function (response) {
            alert(response);
        }
        error:function(){
            alert("failure");
        }
    }); 
}
</script>

Try this in your views.py:

import json
from django.http import HttpResponse

def ajax(request):
    if request.method == 'POST':
        return HttpResponse({'message':'Hello Ajax'}, content_type = "application/json")
0

精彩评论

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