2014-01-24 9 views
1

這是我的觀點:Ajax,jQuery,Django。這是如何獲得設置?

def planning(request): 
    if not request.user.is_authenticated(): 
     return HttpResponseRedirect(reverse('loginregistration.views.login')) 

    if request.is_ajax: 
     POST = request.POST 
     msg = "Success" 
     print request.POST 
     return HttpResponse(msg) 
    else: 
     form = planForm() 
     return render(request, 'plan.html', {'form':form}) 

這裏是我的html:

{% extends "base.html" %} 
{% block title %}Plan{% endblock %} 

{% block content %} 
    <a>Welcome to planning</a> 
    {{form.as_p}} 
    <script> 
    <----- I need to know how to set this up ----> 
    </script> 
{% endblock %} 

我明白我需要做一個按鈕,點擊時提交我的形式,而是從例子中我見過的互聯網它不是很直觀。有人可以給我一個例子,我將如何得到這個頁面上的一個按鈕來發送ajax呼叫到服務器。

編輯: 我該如何鉤住這個按鈕?

{% extends "base.html" %} 
{% block title %}Plan{% endblock %} 

{% block content %} 
    <a>Welcome to planning</a> 
    {{form.as_p}} 
    <button id="form_submit">Submit</button> 
    <script> 
     $('button#form_submit').click(function() { 
     $.ajax({ 
      type: "POST", 
      url:"/planning/submit/", 
      data: { 
       'test': 'success', 
      }, 
      success: function(){ 
       alert('test') 
      }, 
      error: function(){ 
       alert("Error"); 
     }); 
    </script> 
{% endblock %} 

回答

0

有很多方法來實現這一點,但這裏有一個,記住你沒有在<form>屬性太多的控制:

你會做一個按鈕,像這樣:

<button id="form_submit">Submit</button> 

然後,<script>標籤內,類似的信息(使用一些jQuery的):

$('button#form_submit').click(function() { 
    $.ajax({ 
     type: "POST", 
     url:"/planning/submit/", 
     data: $("#form_id").serialize(), 
     success: function(){ 
      alert('test') 
     }, 
     error: function(){ 
      alert("Error"); 
    }); 
}); 

看起來你只是錯過了最後的});,你應該序列化表單數據發送它(用你的表單的id替換form_id)。

+0

不適用於ajax – user3043594

+0

這是什麼意思? – sundance

+0

request.is_ajax!= request.method =='POST':這不適用於$ .post – user3043594