ajax传递数据时的表单系列化方法.serialize()

来源:互联网 发布:快思聪中控编程 人员 编辑:程序博客网 时间:2024/05/22 03:44
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>ajax表单序列化</title><script type="text/javascript" src="jQuery.js"></script><script type="text/javascript">$(function(){$('input').on('click',function(){$.ajax({type: 'POST',url: 'jinwen.php',data: {url:'jinwen'},success: function(response,status,xhr){console.log(status);if ( status == 'success' ){$('#box').html('你们说谁最帅气啊:当然是' + response);}}});});//ajax应用最多的地方莫过于表单操作,传统的表单操作是通过submit提交将数据传输到服务器端。如果使用Ajax异步处理的话,我们需要把//每一个表单元素获取到才能够提交,这样工作效率就会大大降低,。 $('form input[type=button]').on('click',function(){ $.ajax({ type: 'POST', url: 'jinwen.php', data: { user: $('form input[type=text]').val(), email: $('form input[type=email]').val() }, success: function( response, status, xhr ){ console.log(status); $('body').html('全国最帅的人是谁啊?当然是' + response + '!'); } }); }); //下面是使用表单序列化的方法,使用表单序列化方法.serialize(),会智能的获取指定表单内的所有元素。这样,在面对 大量表单元素时,会把表单元素内容序列化为字符串,然后再使用 Ajax 请求。  $('form input[type=button]').on('click',function(){ $.ajax({ type: 'POST', url: 'jinwen.php', data: $('form').serialize(), success: function(response, status, xhr){ console.log(status); $('body').html('你们不说我也知道国内是' + response); } }); }); //.serialize()方法不但可以序列化表单内的元素,还可以直接获取单选框、复选框和下拉 列表框等内容。 //使用序列化得到选中的元素内容 $(':radio').click(function(){ $('#box').html(decodeURIComponent($(this).serialize())); }); $('form input[type=radio]').on('click',function(){ console.log(decodeURIComponent($(this).serialize())); });});</script></head><body><input type="button" value="异步获取数据"/><div id="box"></div><form action="">用户名:<input type="text" name="user" />邮箱:<input type="email" name="email" /><input type="button" value="提交" /><input type="radio" value="男" />男</form></body></html>

0 0