HOWTO · jQuery

Ajax jQuery で get()メソッドを使用する

このチュートリアルでは、get()メソッドを使用して AjaxjQuery で 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 Get Request

数値の乗算テーブルを表示する 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 Get リクエスト