我正在学习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...
我希望当用户单击“提交”按钮时,在“ #output” div中显示PHP中不同的变量值。
我尝试了很多不同的东西(没有jQuery的AJAX,带有jQuery的AJAX),但没有设法得到我想要的东西。
我确定我做错了什么,但我不知道该怎么办。我确定我的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);
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句