问题
Will using <form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
cause the whole page to refresh when the user clicks submit? Or just the PHP part?
回答1:
The page usually will reload after submitting a form to display the response that is received after submitting the form.
To prevent that you got two ways:
- Use
target=_blank
in your form tag
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" target="_blank">
- Use
event.preventDefault();
to prevent the default action of form and then send data manually withfetch
or if you use JQuery you might go withajax
. (I will go with fetch standard API)
document.getElementByTagName("form")[0].addEventListener('submit', function(event) {
event.preventDefault();
const url = 'https://randomuser.me/api';
// The data we are going to send in our request
const data = {
name: 'Sara'
}
// The parameters we are gonna pass to the fetch function
const fetchData = {
method: 'POST',
body: data,
headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
// Handle response you get from the server
});
});
来源:https://stackoverflow.com/questions/61586898/do-php-form-submissions-cause-the-whole-file-to-refresh