[英]Refresh div after form submitting with AJAX
我確實有一個簡單的表單,我使用 ajax 將數據提交到我的數據庫。 一切正常。 現在提交表單后,我收到一條帶有“完成”文本的警報消息。
我唯一的問題是,我的 div 現在應該自動重新加載,因此用戶可以在單擊警報消息中的“確定”按鈕后立即看到發布的結果。 有人可以告訴我如何實現這一目標嗎? 這是我的代碼。
$(function() {
$('#form2').on(\"submit\", function(event) {
event.preventDefault();
$.ajax({
url: 'index.php',
type: 'post',
data: $(this).serialize(),
beforeSend: function(){
$('#loading').show();
},
complete: function(){
$('#loading').hide();
},
success: function() {
alert('Done');
}
});
});
});
<div id='refreshtodo'>
<form name='form2' id='form2' action='./index.php' method='post'>
<input type='text' class='big' name='duedate' size='10' maxlength='10' value='".date("d.m.Y")."'>
<input type='submit' class='btn btn-info btn-sm' role='button' value='add'>
<div id='loading' style='display:none;'>
<img src=\"./bootstrap/assets/images/spinner-loading-small.gif\" alt=\"Loading - Please wait...\" />
</form>
</div>
DIV #refreshtodo
應重新加載,一旦在警報消息中單擊“確定”!
你應該echo
你想在你的div來顯示結果index.php
,例如:
//your index code
...
echo "this is the result".
然后在您的 js 中,您應該只在 div #refreshtodo
打印從 php 頁面返回的result
:
....
success: function(result) {
alert('Done');
$("#refreshtodo").html(result);
}
希望這可以幫助。
您需要將響應數據插入到 HTML (DOM) 中。
試試這個 JS
$(function() {
$('#form2').on(\"submit\", function(event) {
event.preventDefault();
$.ajax({
url: 'index.php',
type: 'post',
data: $(this).serialize(),
success: function(response) {
$('#refreshtodo').html(response);
}
});
});
});
但是,這將從 HTML 中刪除您的表單。 我建議使用不同的 ID(例如“#todo-response”)創建第二個 div 並在那里顯示響應。
您還需要確保您的 PHP 腳本返回您希望顯示的 HTML 內容。
我希望這有幫助。
您的ajax
是否返回您想要輸入到表單中的任何內容? 它是否返回 HTML 或 json/xml?
如果是 HTML
success: function(data) {
alert('Done');
$('#refreshtodo').html(data);
}
JSON 需要您手動將數據從對象映射到表單元素中的值。
目前, #refresthtodo
只有一個表格。 因此,如果您只想重置表單:
var form = document.getElementById("form2");
form.reset();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.