HOWTO · jQuery

jQuery AJAX 資料

本教程演示瞭如何在 jQuery AJAX 中使用資料。

AJAX 資料是傳送到伺服器並由伺服器使用的資料。本教程演示如何在 jQuery 中使用 AJAX 將資料傳送到伺服器。

jQuery AJAX 資料

使用 AJAX 傳送到伺服器的資料可以是 JSON 物件、字串或陣列。此資料會在伺服器頁面上進一步用於任何目的。

我們可以使用陣列或 JSON 物件傳送單個或多個資料。我們使用下面的語法將多個資料欄位與陣列一起傳送。

data: {username: username, password: password}

該方法可以向伺服器傳送多個資料欄位,我們可以將它們用於進一步的處理。在這種情況下,JSON 物件更方便,我們可以在序列化的 JSON 物件中傳送所有資料欄位。

讓我們嘗試一個使用 JSON 物件傳送多個資料欄位的示例。參見示例:

index.html

<!doctype html>
<html>
<head>
<title>jQuery Ajax Data</title>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form id="Login_Form" method="post">
    <div>
        Enter the Username:
        <input type="text" name="username" id="User_Name" />
        Enter the Password:
        <input type="password" name="password" id="Password" />
        <input type="submit" name="loginBtn" id="Login_Button" value="Login" />
    </div>
</form>
<script type="text/javascript">
$(document).ready(function() {
    $('#Login_Form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: 'demo.php',
            data: $(this).serialize(),
            success: function(response) {
                var JSON_Data = JSON.parse(response);
                // user login check
                if (JSON_Data.success == "1" && JSON_Data.username == "admin" && JSON_Data.password == "password" )
                {
                    document.write('Login Success');
                    alert(response);
                }
                else
                {
                    alert('Invalid User Name and Password!');
                }
           }
       });
    });
});
</script>
</body>
</html>

上面的程式碼使用 $.ajaxpost 方法將表單資料傳送到伺服器,伺服器將使用這些資料進行登入;使用 data: $(this).serialize(), 語法在序列化物件中傳送資料。這是 demo.php 伺服器頁面。

<?php
if (isset($_POST['username']) && $_POST['username'] && isset($_POST['password']) && $_POST['password']) {
    //Here we can also perform authentication
    echo json_encode(array('success' => 1, 'username' => $_POST['username'], 'password' => $_POST['password'] ));
} else {
    echo json_encode(array('success' => 0));
}
?>

伺服器程式碼檢查是否設定了使用者名稱和密碼,然後建立一個 JSON 物件以傳送回 AJAX。我們在 index.html 頁面上驗證了 jQuery 中的登入。

請參閱下面動畫中程式碼的輸出。

jQuery Ajax 資料