2 回答

TA貢獻1803條經驗 獲得超6個贊
如果您使用Fetchapi 并向 PHP 腳本發送 POST 請求,您可以嘗試這樣的操作 - 未經測試:
<?php
# calendar.php ~ obviously there will need to be MORE code than this...
if( SERVER['REQUEST_METHOD']=='POST' && isset($_POST['year'],$_POST['month']) ){
#ensure no extra data is sent back - flush buffers
ob_clean();
#send a response
exit( createCalendar( $_POST['year'], $_POST['month'] ) );
}
?>
以及使用 Javascript 發送 AJAX 請求Fetch
let next = document.getElementById("buttonNext");
let monthNb = String(new Date().getMonth() + 1).padStart(2, '0');
let yearNb = new Date().getFullYear();
next.addEventListener("click", function(event) {
monthNb++;
If (monthNb > 12) {
yearNb++;
}
let fd=new FormData();
fd.append('year',yearNb);
fd.append('month',monthNb);
fetch( '/path/to/calendar.php', {method:'post',body:fd})
.then( res=>res.text() )
.then( text=>{
document.getElementById("calendarContainer").innerHTML=text
})
});

TA貢獻1784條經驗 獲得超2個贊
有很多方法可以執行 ajax 并進行許多優化,但我為您提供了如何執行此操作的簡單指南。最簡單的方法是在 Web 服務器中創建一個 php 文件,將其命名為 ajax.php,其內容為
<?php echo createCalendar($_GET['year'], $_GET['month']); ?>
然后,在您的 js 代碼中對該 ajax.php 文件進行 ajax 調用,例如:
let next = document.getElementById("buttonNext");
let monthNb = String(new Date().getMonth() + 1).padStart(2, '0');
let yearNb = new Date().getFullYear();
next.addEventListener("click", function(event) {
monthNb++;
If (monthNb > 12) {
yearNb++;
}
fetch(`ajax.php?year=${yearNb}&month=${monthNb}`, {
method: 'GET',
headers:{
'Content-Type': 'application/json'
},
})
.then(response => {
document.getElementById("calendarContainer").innerText = response;
}).catch(error => console.error('Error:', error));
});
- 2 回答
- 0 關注
- 153 瀏覽
添加回答
舉報