form表单ajax提交json数据

来源:csdn博客 分类: 文章浏览史 发布时间:2020-04-08 12:29:57 最后更新:2020-04-08 浏览:73
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2020-04-08 12:29:57

前端页面:

<form id="userInfo" >
        <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">姓名</label></div>
            <div class="weui-cell__bd">
                <input class="weui-input" id="username" name="username" type="text" pattern="[0-9]*" placeholder="请输入姓名">
            </div>
        </div>
        <div class="weui-cell ">
            <div class="weui-cell__hd">
                <label class="weui-label">年龄</label>
            </div>
            <div class="weui-cell__bd">
                <input class="weui-input" id="age" name="age" type="number" placeholder="请输入年龄">
            </div>
        </div>
        <div class="weui-cell ">
            <div class="weui-cell__hd">
                <label class="weui-label">地址</label>
            </div>
            <div class="weui-cell__bd">
                <input class="weui-input" id="address" name="address" type="text" placeholder="请输入地址">
            </div>
        </div>
        <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary" href="javascript:" id="saveUserInfo">确定</a>
        </div>
    </form>

ajax请求发送数据

 $("#saveUserInfo").click(function() {
        var formObject = {};
        var formArray =$("#userInfo").serializeArray();
        $.each(formArray,function(i,item){
            formObject[item.name] = item.value;
        });
        $.ajax({
            url:"user/addUser",
            type:"post",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formObject),
            dataType: "json",
            success:function(data){
                alert(data.msg);
            },
            error:function(e){
                alert("错误!!");
            }
        });
    });
php技术微信