我正在嘗試在提交表單時顯示一個 div。它在提交表單時顯示 div,而未提交表單。這里使用 POST 方法。JavaScript 用于顯示 div。
.html 檔案:
<form method="POST" name="myFirstForm" id="chform">
{% csrf_token %}
<input type="hidden" name="details_id" value="{{details.id}}"/>
<input type="hidden" name="details_user_id" value="{{details.user_id}}"/>
<input type="hidden" name="user_id" value="{{user.id}}"/>
<input type="submit" class="btn btn-danger" id="chat" onclick="return myFunction()" value="Chat Now">
</form>
<div class="page-content page-container" id="page-content" style="display:none"></div>
JavaScript:
<script>
document.forms['myFirstForm'].addEventListener('submit', function(event) {
// Do something with the form's data here
this.style['display'] = 'none';
event.preventDefault();
});
function myFunction() {
var x = document.getElementById("page-content");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
視圖.py:
if request.method=='POST':
jid = request.POST.get('details_id')
print(jid)
cjid = request.POST.get('details_user_id')
print(cjid)
userid = request.POST.get('user_id')
print(userid)
如果我不想顯示 div 并洗掉 JavaScript 代碼,POST 方法可以作業。任何人都可以提出解決此問題的解決方案嗎?
uj5u.com熱心網友回復:
您是否考慮過異步 JavaScript 和 XML (AJAX)?聽起來你想要異步 JS 功能(或者我沒有正確理解)。
因此,在您的提交按鈕中,您將使其呼叫 AJAX 函式,如下所示:
<button type="submit" id="chat" data-url="{% url 'url_to_your_view_handling_the_post' %}" value="Chat Now"></button>
然后你的onclick功能:
$(document).on('click', '#chat', function (e) {
$.ajax({
type: 'POST',
url: $(this).data('url'),
data: {
// add any other HTML data attributes in this dictionary
csrfmiddlewaretoken: getCookie('csrftoken'),
},
success: function (json_response) {
// Successful AJAX response handling routine here
// Display your div
var x = document.getElementById("page-content");
if (x.style.display === "none") {
x.style.display = "block";
}
else {
x.style.display = "none";
}
},
error: function (xhr, errmsg, err) { }
});
})
因此,您url_to_your_view_handling_the_post在按鈕中定義的url 上的視圖將處理 POST 方法并回傳包含您想要的任何資料的 JSON 回應。如果成功回傳,則運行 AJAX 函式中的成功例程。
發送 csrf 令牌并不是非常簡單,我建議您參閱此執行緒以了解有關該getCookie('csrftoken')功能的更多資訊。
注意:這是 AJAX 的 jquery 實作,因此您還需要在模板中包含 jquery。
uj5u.com熱心網友回復:
如果你想提交表單,那么你不應該呼叫event.preventDefault();. 這基本上告訴 js 捕獲submit事件并阻止事件的默認行為,即在您的情況下提交表單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406575.html
標籤:
