2016-04-25 18 views
0

我有一個Django的形式,如:jQuery的AJAX調用重定向到URL稱爲同insted的模板

<form class="myform" action="{% url "create" %}" method="post">{% csrf_token %} 
    <div class="results"></div> 
    <label class="input margin-bottom-10">{{form.name}} 
    <div class="name_error"></div> 
    </label> 
    <label class="input margin-bottom-10">{{form.age}} 
    <div class="age_error"></div> 
    </label> 
    <input class="margin-top-10 pull-right" type="submit" value="Confirm" > 
</form> 

和我的jQuery是這樣的:

frm = $('.myform') 
frm.on('submit', function(event){ 
    create(frm); 
}); 



function create(frm) { 
    $.ajax({ 
     url : frm.attr('action'), // the endpoint 
     type : frm.attr('method'), // http method 
     data: frm.serialize(), // data sent with the post request 

     // handle a successful response 
     success : function(response) { 
      if(response.status == "success"){ 
       var success_message = "<div>some success message</div>) 
       $('#container_body').html(success_message); 
      }; 

      if(response.status == "error"){ 
       frm.find('.results').html("<div class='alert alert-mini alert-danger'>"+response.message+"</div>"); 
      }; 
     }, 
    }); 
}; 

這裏我Ajax調用是做好事。我正在得到正確的迴應,但DOM操作是錯誤的。

當我點擊提交按鈕,並出現錯誤。我想在.results類中顯示錯誤消息。

當出現錯誤時,帶有錯誤的表單會顯示一段時間,然後消失,並顯示帶有json響應的我的網頁。

我的表單有錯誤消息沒有留下來,並用json響應重定向到url頁面。

這裏有什麼問題

+0

您是否需要將整個表單作爲參數傳遞?你可以簡單地通過表單屬性而不是形式 – brk

+0

''input class =「margin-top-10 pull-right」type =「button」value =「Confirm」>' – Rayon

+0

'type =「submit」'將提交();'使用'e.preventDefault();' – Rayon

回答

1

你的腳本有JS錯誤並被提交。這是你需要做的解決這個問題。閱讀行內評論。

frm.on('submit', function(event){ 
    event.preventDefault(); //Prevents the default action from happening and Rayon mentioned 
    create(frm); 
}); 

修復成功函數中的JS錯誤。記住JS錯誤可能會使整個應用程序失敗。

success : function(response) { 
     if(response.status == "success"){ 
      var success_message = "<div>some success message</div>"; //This line had error in your code 
      $('#container_body').html(success_message); 
     } //You don't need a semicolon here 

     if(response.status == "error"){ 
      frm.find('.results').html("<div class='alert alert-mini alert-danger'>"+response.message+"</div>"); 
     } //You don't need a semicolon here 
    }// You dont need the redundant comma here which will error out in IE