2

I know, you have read questions like this a thousand times or even more often, and I have also read these questions and their answers, but I simply cannot get my AJAX form to work correctly using jQuery on the client side and Django on the server side. Also, I was not able to find a stupid simple step-by-step tutorial for a Python guy and JavaScript newbie like me which is understandable and detailed enough to give me the aha moment that I'm so eagerly waiting for.

I have a form on a HTML page and when clicking the submit button, the respective HttpResponse should simply be alerted using JavaScript's alert() function, but it doesn't work. When I submit the form, I find the following entry in Django's development server console:

"POST /ajaxtest/%5Bobject%20Object%5D HTTP/1.1" 404 2381

Please tell me what's wrong with my code. Thank you very much in advance!

forms.py

from django.db import forms

class AjaxTestForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()

views.py

from django.http import HttpResponse
from django.shortcuts import render
from my_app.forms import AjaxTestForm

def ajax_test(request):
    if request.is_ajax() and request.method == 'POST':
        form = AjaxTestForm(request.POST)
        if form.is_valid():
            print request.POST
            # I want this to be alerted
            return HttpResponse('Your AJAX form test was successful!')
        else:
            return HttpResponse('Your AJAX form test failed miserably!')
    else:
        form = AjaxTestForm()

    return render(request, 'ajaxtest.html', {'form': form})

urls.py

from django.conf.urls import patterns, url
from my_app.views import ajax_test

urlpatterns = patterns('',
    url(r'^ajaxtest/$', ajax_test, name='ajax-test-page')
)

ajaxtest.html

<!DOCTYPE html>
<html>
<head>
    <script src="{{ STATIC_URL }}js/jquery-1.8.2.min.js"></script>

    <script>

        $(document).ready(function() {

            $('#ajaxform').submit(function(event) {

                var $form = $(this);
                var serializedData = $form.serialize();

                $.post({
                    url: '/ajaxtest/',
                    data: serializedData,
                    success: function(response) {
                        alert(response);
                    }
                });

                event.preventDefault();

            });
        });

    </script>
</head>

<body>
    <form id="ajaxform" method="post" accept-charset="UTF-8" action="">{% csrf_token %}

        <fieldset>
            {% for field in form %}
                <label for="{{ field.label }}">{{ field.label }}</label>
                <input id="{{ field.label }}" type="text" name="{{ field.html_name }}" />
            {% endfor %}

            <button type="submit">Submit</button>
        </fieldset>

    </form>
</body>
</html> 
4

1 に答える 1

7

手がかりはコンソール[object Object]にあります。POST 先の URL に追加されていることを示しています。それが関数に渡したオブジェクト全体の表現だと思います$.post

これは、$.ajax関数とは異なり$.post、オブジェクトを取らず、個々のパラメーターを取るためです。したがって、コードは次のようになります。

$.post('/ajaxtest/', serializedData, function(response) {
   alert(response);
});
于 2012-11-16T14:21:23.470 に答える