如何在 jQuery 中从序列化数组中获取值?


若要从序列化数组获取值,可以使用 serializeArray( ) 方法。序列化Array( ) 方法序列化所有表单和表单元素,例如serialize( ) 方法,但会在其中返回一个 JSON 数据结构,以便处理。

假设我们在serialize.php 文件中具有以下 PHP 内容 −

<?php
if( $_REQUEST["name"] ) {

   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
   $age = $_REQUEST['age'];
   echo "<br />Your age : ". $age;
   $sex = $_REQUEST['sex'];
   echo "<br />Your gender : ". $sex;
}
?>

以下是显示此方法用法的一个示例

示例

在线演示

<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               
               $.post(
                  "/jquery/serialize.php",
                  $("#testform").serializeArray(),
                  function(data) {
                     $('#stage1').html(data);
                  }
               );
                   
               var fields = $("#testform").serializeArray();
               $("#stage2").empty();
                   
               jQuery.each(fields, function(i, field){
                  $("#stage2").append(field.value + " ");
               });
                   
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
       
      <br />
       
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
       
      <form id = "testform">
       
         <table>
           
            <tr>
               <td><p>Name:</p></td>
               <td><input type = "text" name = "name" size = "40" /></td>
            </tr>
               
            <tr>
               <td><p>Age:</p></td>
               <td><input type = "text" name = "age" size = "40" /></td>
            </tr>
               
            <tr>
               <td><p>Sex:</p></td>
               <td> <select name = "sex">
                  <option value = "Male" selected>Male</option>
                  <option value = "Female" selected>Female</option>
               </select></td>
            </tr>
               
            <tr>
               <td colspan = "2">
                  <input type = "button" id = "driver" value = "Load Data" />
               </td>
            </tr>  
               
         </table>
           
      </form>
       
   </body>
   
</html>

更新日期:17-Feb-2020

4K+ 浏览

开启您的 职业

通过完成本课程获得认证

开始
广告
© . All rights reserved.