• jQuery使用serialize(),serializeArray()方法取得表单数据+字符串和对象类型两种表单提交的方法


    原始form表单值获取方式(手动):
    $.ajax({
       type: "POST",
       url: "ajax.php",
       data: "Name=摘取天上星&position=IT技术",
       success: function(msg){alert(msg);},
       error: function(error){alert(error);}
     });
    JQ serialize()方法取值:
    $.ajax({
       type: "POST",
       url:"ajax.php",
       data:$('#formID').serialize(),// 要提交的表单
       success: function(msg) {alert(msg);},
       error: function(error){alert(error);}
    });
    serialize()序列化表单实例:
    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    $(function(){
       $("#button").click(function(){
         alert($("#formID").serialize());
       });
    });
    </script>
    <form id="formID">
        姓名 <input value="摘取天上星" name="Name" />
        职位 <input value="IT技术" name="position" />
            <input id="button" value="提交" type="button" />
    </form>

     将form中的值转换为键值对:

    // 如:{Name:'摘取天上星',position:'IT技术'}
    // ps:注意将同名的放在一个数组里
    function getFormJson(form) {
    	var o = {};
    	var a = $(form).serializeArray();
    	$.each(a, function () {
    		if (o[this.name] !== undefined) {
    			if (!o[this.name].push) {
    				o[this.name] = [o[this.name]];
    			}
    			o[this.name].push(this.value || '');
    		} else {
    			o[this.name] = this.value || '';
    		}
    	});
    	return o;
    }
    键值对方式的AJAX调用:
    //调试调用 
    $(function(){
    	$("#button").click(function(){
    		alert(getFormJson("#formID"));
    	});
    });
    //Ajax提交
    $.ajax({
       type: "POST",
       url:"ajax.php",
       data:getFormJson($("#formID")),//表单数据JSON格式的函数參数里填写表单的ID或要提交的表单
       dataType: 'json',
       success: function(msg) {alert(msg);},
       error: function(error){alert(error);}
    });
    实例中通用的HTML表单:
    <form id="formID">
        姓名 <input value="摘取天上星" name="Name" />
        职位 <input value="IT技术" name="position" />
            <input id="button" value="提交" type="button" />
    </form>




  • 相关阅读:
    安装 pptpd 服务
    profile bashrc bash_profile 之间的区别和联系
    11款基于Javascript的文件管理器
    C/C++学习之static_cast和dynamic_cast、reinterpret_cast
    VS.Net中程序集的Debug版本和Release版本的区别
    .net4.0以下的CookieContainer存在一个bug.即主域和子域cookie互访有问题。
    学习C# delegate和C# event
    使用log4net记录日志到数据库(含有自定义属性)
    c#获取本机ip地址|获取本机的本地上网IP地址
    Java 跨语言实现方案
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/7309235.html
Copyright © 2020-2023  润新知