当我单击按钮时,如何在当前页面上回显 php 脚本的响应?我知道如何在不离开页面的情况下运行 php 脚本。问题是响应 ( echo
) 未显示在用户所在的页面上。我当前的解决方案是从表单调用当前站点并像这样处理响应,但是是否可以在不刷新页面的情况下做到这一点?
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<form class="form" action="index.php" method="post">
<input type="text" class="textfield" name="message" id="message">
<input type="submit" class="button" value="send">
</form>
</body>
</html>
通常我会使用 Javascript 来完成类似的任务,但在这种情况下我必须使用 php。我还尝试对 php 文件发出 JS post 请求,但这个解决方案感觉不“干净”。
最佳答案
您可以像使用 PHP 一样使用 Ajax 表单提交脚本。
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div class="alert-msg"></div>
<form class="form" id="myForm" action="index.php" method="post">
<input type="text" class="textfield" name="message" id="message">
<input type="submit" class="button submit-btn" value="send">
</form>
// you can use add this script in body tag
<script type="text/javascript">
// ------- Mail Send ajax
$(document).ready(function() {
var form = $('#myForm'); // contact form
var submit = $('.submit-btn'); // submit button
var alert = $('.alert-msg'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'index.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.attr("style", "display: none !important");; // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
</script>
</body>
</html>
关于javascript - 如何在不离开页面的情况下通过单击按钮显示 php 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726521/