JQuery中的param()、 serialize() 和serializeArray()方法

    xiaoxiao2025-03-26  19

    1、param方法

    param() 方法创建数组或对象的序列化表示形式。序列化的值可在生成 AJAX 请求时用于 URL 查询字符串中。        语法:$.param(object,trad) object:必需。规定要序列化的数组或对象。 trad:可选。布尔值,指定是否使用参数序列化的传统样式。

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <script src="js/jquery-3.1.0.js"> </script> <script> $(document).ready(function(){     personObj=new Object();     personObj.firstname="John";     personObj.lastname="Doe";     personObj.age=50;     personObj.eyecolor="blue";      $("button").click(function(){       $("div").text($.param(personObj));     });   });   </script> <style> div{ width:450px; margin-top: 20px; border: solid grey 2px; padding: 5px; border-radius: 10px; text-align: center; background-color:yellowgreen; color: white; } </style> </head> <body> <button>序列化对象</button>   <div></div>  </body> </html>

    2、serialize方法

      serialize() 方法通过序列化表单值创建 URL 编码文本字符串。可以选择一个或多个表单元素(如输入和/或文本区),或表单元素本身。序列化的值可在生成 AJAX 请求时用于 URL 查询字符串中。     语法:$(selector).serialize()

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <script src="js/jquery-3.1.0.js"> </script> <script> $(document).ready(function(){   $("button").click(function(){     $("div").text($("form").serialize());   }); }); </script> <style> <pre code_snippet_id="1828985" snippet_file_name="blog_20160814_1_9126200" name="code" class="html">div{ width:450px; margin-top: 20px; border: solid grey 2px; padding: 5px; border-radius: 10px; text-align: center; background-color:yellowgreen; color: white; }</style></head><body><form action="">姓名: <input type="text" name="Name" value="Zou Miao" /><br><br>学校: <input type="text" name="School" value="KunGong" /><br><br>时间: <input type="date" name="Time"/><br><br>邮箱: <input type="email" name="Email"/><br><br></form><br><button>序列化表单值</button><div></div></body></html>

    3、serializeArray方法

      serializeArray() 方法通过序列化表单值来创建对象(name 和 value)的数组。可以选择一个或多个表单元素(如输入和/或文本区),或表单元素本身。     语法:$(selector).serializeArray()

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <script src="js/jquery-3.1.0.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ x=$("form").serializeArray(); $.each(x, function(i, field){ $("#results").append(field.name + ":" + field.value + " "); }); }); }); </script> <style> div{ width:450px; margin-top: 20px; border: solid grey 2px; padding: 5px; border-radius: 10px; text-align: center; background-color:yellowgreen; color: white; } </style> </head> <body> <form action=""> 姓名: <input type="text" name="Name" value="Zou Miao" /><br><br> 学校: <input type="text" name="School" value="KunGong" /><br><br> 时间: <input type="date" name="Time"/><br><br> 邮箱: <input type="email" name="Email"/><br><br> </form><br> <button>序列化表单值</button> <div id="results"></div> </body> </html>

    转载请注明原文地址: https://ju.6miu.com/read-1297395.html
    最新回复(0)