2012-11-16 50 views
2

我知道,你已經閱讀過這樣的問題一千次甚至更多,並且我也閱讀了這些問題和他們的答案,但我無法讓我的AJAX表單在客戶端和Django上使用jQuery正確工作服務器端。此外,我無法爲像我這樣的Python人員和JavaScript新手找到一個愚蠢簡單的循序漸進的教程,這個教程足以理解並詳細描述我給出的那個我急切等待的時刻。我的Django&jQuery AJAX表單提交設置有什麼問題?

我在HTML頁面上有一個表格,當點擊提交按鈕時,應該使用JavaScript的alert()函數簡單地提醒各自的HttpResponse,但它不起作用。當我提交表單,我發現在Django的開發服務器控制檯輸入以下內容:

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

請告訴我什麼是錯我的代碼。非常感謝您提前!

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> 

回答

7

的線索是在控制檯:它的顯示,它的附加[object Object]將其調職的URL。我懷疑這是你傳遞給$.post函數的整個對象的表示。

這是因爲與$.ajax函數不同,$.post不帶對象,它需要單獨的參數。所以你的代碼應該是:

$.post('/ajaxtest/', serializedData, function(response) { 
    alert(response); 
}); 
$.post('/ajaxtest/', serializedData, function(response) { 
    alert(response); 
}); 
+0

哦,親愛的......我確信它必須是一個愚蠢的錯誤,但我不認爲這會是那麼愚蠢。當您還沒有習慣JavaScript語法時,會發生類似的情況。你拯救了我的一天。非常感謝! :) – pemistahl