帶有 Ajax 的 PHP
Kevin Amayi
2023年1月30日
我們將通過列印兩個數字 2
和 3
的簡單總和來使用 PHP 和 ajax。此外,在 JSON object
中列印一個 php 陣列。
我們還將通過從 PHP 的數字除法獲取 HTML 格式的輸出來使用帶有 ajax 的 PHP。
使用 PHP 和 Ajax 列印兩個數字之間的簡單加法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.get("summation.php", function(data){
console.log(data);
});
});
</script>
</body>
</html>
<?php
$number1 = 2;
$number2 = 3;
$summation = $number1 + $number2;
echo "Summation, $summation";
?>
輸出:
Summation, 5
使用帶有 Ajax 的 PHP 以 JSON 物件的形式列印 PHP 陣列
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.get("json.php", function(data){
console.log(data);
});
});
</script>
</body>
</html>
<?php
$profile = array('name' => "Kevin Amayi", "age" => 23, "Profession" => "Programmer");
echo json_encode($profile);
?>
輸出:
{"name":"Kevin Amayi","age":23,"Profession":"Programmer"}
使用 PHP 和 Ajax 列印數字除以 1-20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax and PHP Basics</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var number = $("#number").val();
$.get("division.php", {number: number} , function(data){
$("#division").html(data);
});
});
});
</script>
</head>
<body>
<label>Enter a Number: <input type="number" id="number"></label>
<button type="button">Show Division Table</button>
<div id="division"></div>
</body>
</html>
<?php
$number =$_GET["number"];
//check if the data entered is a number => if so display a table with the number's division from 1-20
if(is_numeric($number) ){
echo "<table>";
for($j=1; $j<21; $j++){
echo "<tr>";
echo "<td>$number / $j</td>";
echo "<td>=</td>";
echo "<td>". $number / $j . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
輸出:
2 / 1 = 2
2 / 2 = 1
2 / 3 = 0.66666666666667
2 / 4 = 0.5
2 / 5 = 0.4
2 / 6 = 0.33333333333333
2 / 7 = 0.28571428571429
2 / 8 = 0.25
2 / 9 = 0.22222222222222
2 / 10 = 0.2
2 / 11 = 0.18181818181818
2 / 12 = 0.16666666666667
2 / 13 = 0.15384615384615
2 / 14 = 0.14285714285714
2 / 15 = 0.13333333333333
2 / 16 = 0.125
2 / 17 = 0.11764705882353
2 / 18 = 0.11111111111111
2 / 19 = 0.10526315789474
2 / 20 = 0.1