使用 Ajax jQuery 的 get() 方法

jQuery 中的 get() 方法向服务器发送异步 GET 请求以检索数据。本教程演示了在 Ajax jQuery 中使用 get() 方法。

在 Ajax jQuery 中使用 get() 方法

如上所述,jQuery 中的 get() 在 Ajax 中用于向服务器发送 GET 请求。

语法:

$.get(url, [data],[callback])

url 是我们将从中检索数据的请求 URL。data 是将通过 GET 请求发送到服务器的数据,callback 是将在请求成功时执行的函数。

让我们创建一个简单的 get() 示例,它将转到 demo.php 并打印在警报中检索到的数据。

代码 – HTML:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("demo.php", function(Get_Data, Get_Status){
            alert("Data Retrieved: " + Get_Data + "\n GET Status: " + Get_Status);
        });
    });
});
</script>
</head>
<body>
    <button>Send an HTTP GET request to demo.php</button>
</body>
</html>

代码 – demo.php 是:

<?php
echo "Hello This is GET request data from delftstack.";
?>

输出:

使用 Ajax jQuery 的 get() 方法

让我们再举一个例子,它会发送 get 请求来显示一个数字的乘法表。

代码 – HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Ajax get() Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var Number_Value = $("#input_number").val();
        // Send input data to the server using get
        $.get("demo.php", {Number: Number_Value} , function(result_data){
            // Display the returned data in browser
            $("#multiply_result").html(result_data);
        });
    });
});
</script>
</head>
<body>
    <label>Enter a Number: <input type="text" id="input_number"></label>
    <button type="button">Press the Button to Show Multiplication Table</button>
    <div id="multiply_result"></div>
</body>
</html>

代码 – demo.php

<?php
$num = htmlspecialchars($_GET["Number"]);
if(is_numeric($num) && $num > 0){
    echo "<table>";
    for($x=0; $x<11; $x++){
        echo "<tr>";
            echo "<td>$num x $x</td>";
            echo "<td>=</td>";
            echo "<td>" . $num * $x . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
?>

输出:

使用 Ajax jQuery 的 get() 方法