Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Lấy giá trị POST từ serializeArray trong PHP

jQuery serializeArray() tạo mảng đối tượng {name, value} từ form, gửi qua AJAX. PHP nhận qua $_POST hoặc $_REQUEST như form thường.

PHP (serialize.php)

<?php
if (isset($_REQUEST["name"])) {
    $name = $_REQUEST['name'];
    echo "Welcome " . $name;
    $age = $_REQUEST['age'];
    echo "<br />Your age: " . $age;
    $sex = $_REQUEST['sex'];
    echo "<br />Your gender: " . $sex;
}
?>

JavaScript/jQuery (Client)

<html>
<head>
    <title>jQuery serializeArray Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        $("#driver").click(function(event){
            $.post(
                "/jquery/serialize.php",
                $("#testform").serializeArray(),
                function(data) {
                    $('#stage1').html(data);
                }
            );
            // Hiển thị giá trị từng field
            var fields = $("#testform").serializeArray();
            $("#stage2").empty();
            jQuery.each(fields, function(i, field){
                $("#stage2").append(field.value + " ");
            });
        });
    });
    </script>
</head>
<body>
    <p>Click button to send data:</p>
    <div id="stage1" style="background-color:maroon;color:white;">STAGE - 1</div>
    <br />
    <div id="stage2" style="background-color:maroon;color:white;">STAGE - 2</div>
    <form id="testform">
        <table>
            <tr><td>Name:</td><td><input type="text" name="name" size="40" /></td></tr>
            <tr><td>Age:</td><td><input type="text" name="age" size="40" /></td></tr>
            <tr><td>Sex:</td><td>
                <select name="sex">
                    <option value="Male" selected>Male</option>
                    <option value="Female">Female</option>
                </select></td></tr>
            <tr><td colspan="2"><input type="button" id="driver" value="Load Data" /></td></tr>
        </table>
    </form>
</body>
</html>

Lưu ý

  • serializeArray() không bao gồm input disabled.
  • PHP truy cập qua key name: $_POST['name'], $_POST['age']...
  • Dùng serialize() nếu chuỗi query string (name=value&...).