[英]submit a form with jQuery function
我有一個html頁面,其中包含一個表單,並且我希望在成功提交表單后顯示以下div:
<div class="response" style="display: none;">
<p>you can download it<a href="{{ link }}">here</a></p>
</div>
我也有一個jQuery函數:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
並在我的views.py
(后面的代碼)中創建一個鏈接並將其傳遞給html頁面。 我有:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
我的問題:看來我的觀點沒有執行。 它沒有顯示我發送到此頁面的鏈接。 似乎只執行jQuery函數。 我糊塗了。 我怎樣才能使它們都執行(我是指jQuery函數,然后是我在此函數中設置的url,這些視圖使我的視圖得以執行。)
我不知道如何使用序列化功能。 每當我搜索時,他們都寫道:
.serialize()方法以標准的URL編碼表示法創建文本字符串,並生成查詢字符串,例如“ a = 1&b = 2&c = 3&d = 4&e = 5”。
我不知道何時需要使用它,而我可以在request.Post [“ field name”]中訪問表單字段。 我不知道應該成功的數據是什么:在我的情況下為function(data)。
非常感謝您的幫助。
您必須從ajax post函數獲取並顯示data
,其中data
是您通過DJango服務器呈現的響應,例如:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
您的JS / jQuery應該變成這樣:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download it<a href="'+data+'">here</a></p>');
$(".response").show();
}
});
});
});
</script>
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.