jquery获取form表单数据

<form id="title">
	<input name='username'>用户名
	<input name='password'>密码
</form>
<button id='submit' type="button">提交</button>
<button id='submit2' type="button">提交</button>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

<script>
	//方法一
	 $("#submit").click(function(){
        //serialize()函数将来自表单的数据转码了,所以需要解码才能显示正常数据
        var title =decodeURIComponent($("#title").serialize());//获取form id=title的表单数据
        console.log(title);
    });
	//方法二
	$("#submit2").click(function(){
    x=$("#title").serializeArray();
    var arrayObj = new Array();
    $.each(x, function(i, field){
    	console.log(field.name+':'+field.value);
    });
});
</script>

在这里插入图片描述
在这里插入图片描述
实战例子:

    <script>
    //当id=submitadd的按钮被点击时
      $("#submitadd").click(function(){
        //serialize()函数将来自表单的数据转码了,所以需要解码才能显示正常数据
        var title =decodeURIComponent($("#title").serialize());//获取form id=title的表单数据
        //获取ckeditor的内容
        var oEditor = CKEDITOR.instances.editor1;
        var content = oEditor.getData();
        //获取复选框内容,复选框name = check
        var checkID=[];
        $("input[name='check']:checked").each(function(i){
              checkID[i] = $(this).val();
                });
        //判断内容是否填写
        if(title=='title='){
          html="<div class='alert alert-warning'><strong>题目没有填写</strong></div>";
          $("#test").html(html);
        }else if(content==''){
          html="<div class='alert alert-warning'><strong>正文没有填写!</strong></div>";
          $("#test").html(html);
        }
        $.ajax({ 
          type:'post',  
          url:'http://127.0.0.1:5000/edit',
          cache: false,
          data:{
            'title':title,
            'text':content,
            'checkID':checkID
            },  //重点必须为一个变量如:data
          contentType: "application/x-www-form-urlencoded; charset=utf-8",
          success:function(data){
          },
          error:function(){ 
           alert("请求失败")
          }
         })
          
      })
    </script>
  1. 在获取title表单时,如果表单为中文,就会出现%4E%此类utf-8的乱码,原因是因为serialize()将编码改变了,所以用decodeURIComponent将其解码
  2.  html="<div class='alert alert-warning'><strong>题目没有填写</strong></div>";
      $("#test").html(html);        
      //需要指定一个<div id='test'></div>才可以显示html	
    

·

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值