[英]What is the best way to pass django form data to javascript ajax call?
我有一個包含一定數量字段並使用 ajax 調用與服務器通信的表單。 我想知道什么是傳遞我從表單的 request.post 獲得的數據並將其傳遞回 ajax 的 javascript 成功屬性的最佳方法。
這是一個例子:
def ajaxView(request):
form = MyForm(request.POST or None)
if request.is_ajax() and form.is_valid():
#1 I used to use render_to_string and Parse it in the js
#2 or get field by field using the request.POST.get method and return it
#3 is to serialize the form
return JsonResponse({})
return ""
在 .js 文件中:
function CreateAjax(e) {
e.preventDefault();
$.ajax({
url: "/ajaxViewUrl/",
type: "post",
data: $("#idForm").serialize(),
success: function (data) {
// if the first option retreive fields by field after parse
},
error: () => {
}
});
}
現在,如果表單的字段數量很少,這將不是問題,我擔心的是當表單有大量字段時,在任何情況下我都想減少重復獲取表單中的輸入值。
需要注意的是將表單作為 html 剪斷到模態返回時。
視圖.py
@require_http_methods(["POST"])
def login(request):
form = BasicLogInForm(request.POST)
if form.is_valid():
print "ITS VALID GO SOMEWHERE"
pass
return render(request, 'assess-beta/login-beta.html', {'loginform':form})
返回截斷的 html 的簡單視圖
表格 html 被截斷
<form class="login-form" action="/login_ajx" method="Post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="header">Authenticate</h4>
</div>
<div class="modal-body">
{%if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{%endif%}
<div class="fieldWrapper form-group has-feedback">
<label class="control-label" for="id_email">Email</label>
<input class="form-control" id="{{ form.email.id_for_label }}" type="text" name="{{ form.email.html_name }}" value="{%if form.email.value %}{{ form.email.value }}{%endif%}">
{%if form.email.errors %}<div class="alert alert-danger">{{ form.email.errors }}</div>{%endif%}
</div>
<div class="fieldWrapper form-group has-feedback">
<label class="control-label" for="id_password">Password</label>
<input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name}}" value="{%if form.password.value %}{{ form.password.value }}{%endif%}">
{%if form.password.errors %}<div class="alert alert-danger">{{ form.password.errors }}</div>{%endif%}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Sign in" class="btn btn-primary pull-right"/>
</div>
</form>
包含模式的頁面
{% include "assess-beta/login-beta.html" %}使用 include 標簽加載頁面加載時的片段,以便在您打開模式時可用。
模態.js
$(document).on('submit', '.login-form', function(){ $.ajax({ type: $(this).attr('method'), url: this.action, data: $(this).serialize(), context: this, success: function(data, status) { $('#LoginModal').html(data); } }); return false; });
在這種情況下使用 the.on() 就像 .live() 一樣,關鍵是將提交事件綁定到文檔而不是按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.