如何通过AJAX请求PHP文件来更改文本值?(不刷新页面)



我正在学习AJAX,并希望创建一个非常简单的web应用程序来使用我的知识;真实世界";。

多亏了AJAX,我正试图计算用户输入值的不同百分比,并使其出现在网页上,而不需要刷新。

这是我的HTML表单:

<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button type="submit">Calculate</button>
</form> 
<div id="#output">This is where I want the result to be shown with AJAX</div>

以下是我的一些PHP代码,供您了解:

# Get the user input (work load in kgs)
if (isset($_POST['userWorkLoad'])) {
$workload = $_POST['userWorkLoad'];
# Avoid JS hacking
$workload = htmlspecialchars($workload);
}
# CALCULATION #
# Calculate 55% of the work load (1st warm up set)
$FirstWarmupSet = ($workload * 0.55);
# Calculate 70% of the work load (2nd warm up set)
$SecondWarmupSet = ($workload * 0.7);
# First Warmup set #
echo "<li>Do 8 reps with " . $FirstWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
# Second Warmup set #
echo "<li>Do 5 reps with " . $SecondWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
// etc etc...

我希望PHP中的不同变量值显示在我的"#输出";div。

我尝试了很多不同的东西(AJAX没有jQuery,AJAX有jQuery(,但都没能得到我想要的。

我确信我做错了什么,但我不知道是什么。我确信我的PHP脚本是有效的,因为我在没有AJAX的情况下使用它没有任何问题。

如果有人能在这方面帮助我,我将不胜感激。

如上所述,为您发出AJAX请求的最简单方法可能是尝试jQuery:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Add jQuery on your HTML page -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Add some custom JavaScript file -->
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button id="btn" type="submit">Calculate</button>
</form> 
<div id="output">This is where I want the result to be shown with AJAX</div>
</body>
</html>

script.js内容:

$(function() {
// Process a button click
$("#btn").click(function() {
event.preventDefault();
// Get input field
var userWorkLoadInput = $("#userWorkLoad");
// Build some request parameters
var params = {
userWorkLoad: userWorkLoadInput.val()
};
// Let's name your PHP script file as "server.php"
// And send POST request with those parameters
$.post("server.php", params, function(response) {
// Response text we're going to put into the `output`
$("#output").html(response);
});
});
});

您可以简单地使用Jquery而不是Ajax(使用PHP,您应该在表单中添加method="POST"(。这里有一个例子:

$(document).ready(function(){
$("#send").click(function(){
// your calculates
$("#output").html(...);
});
});
...
<button type="submit" id="send">Calculate</button>

最新更新