Json填充到Form中

    很多框架都支持将json解释到grid的或者form中,个人手痒,自己写了一个。所用到的内容主要是javascript对json的遍历。如:

  

for (var key in json) {
     alert("name:" + key + " value:" + json[key]);   
}

  而具体到网页中,form中会有一些空间,这就要具体情况具体分析了,废话不说,帖代码

var fillForm = function ($form, json) {
    var jsonObj = json;
    if (typeof json === 'string') {
        jsonObj = $.parseJSON(json);
    }

    for (var key in jsonObj) {  //遍历json字符串
        var objtype = jsonObjType(jsonObj[key]); // 获取值类型

         if (objtype === "array") { //如果是数组,一般都是数据库中多对多关系

            var obj1 = jsonObj[key];
            for (var arraykey in obj1) {
                //alert(arraykey + jsonObj[arraykey]);
                var arrayobj = obj1[arraykey];
                for (var smallkey in arrayobj) {
                    setCkb(key, arrayobj[smallkey]);
                    break;
                }
            }
        } else if (objtype === "object") { //如果是对象,啥都不错,大多数情况下,会有 xxxId 这样的字段作为外键表的id

        } else if (objtype === "string") { //如果是字符串
            var str = jsonObj[key];
            var date = new Date(str);
            if (date.getDay()) {  //这种判断日期是本人懒,不想写代码了,大家慎用。
                $("[name=" + key + "]", $form).val(date.format("yyyy-MM-dd"));
                continue;
            }

            var tagobjs = $("[name=" + key + "]", $form);
            if ($(tagobjs[0]).attr("type") == "radio") {//如果是radio控件 
                $.each(tagobjs, function (keyobj,value) {
                    if ($(value).attr("val") == jsonObj[key]) {
                        value.checked = true;
                    }
                });
                continue;
            }
            
            $("[name=" + key + "]", $form).val(jsonObj[key]);
            
        } else { //其他的直接赋值
            $("[name=" + key + "]", $form).val(jsonObj[key]);
        }

    }
}

var setCkb = function (name, value) {
    //alert(name + " " + value);
    //$("[name=" + name + "][value=" + value + "]").attr("checked", "checked");  不知为何找不到具体标签;
    $("[name=" + name + "][val=" + value + "]").attr("checked", "checked");
}
View Code

由于多选会有一些不同的方式,没办法,只能继续具体情况具体分析

var fillckb = function (name, json) {
    var jsonObj = json;
    if (typeof json === 'string') {
        jsonObj = $.parseJSON(json);
    }
    var str = jsonObj[name];
    if (typeof str === "string") {
        var array = str.split(",");
        $.each(array, function (key, value) {
            setCkb(name, value);
        });
    }
}
View Code

貌似少了判断类型的方法

var jsonObjType = function (obj) {
    if (typeof obj === "object") {
        var teststr = JSON.stringify(obj);
        if (teststr[0] == '{' && teststr[teststr.length - 1] == '}') return "class";
        if (teststr[0] == '[' && teststr[teststr.length - 1] == ']') return "array";
    }
    return typeof obj;
}
View Code

接下来是html中的了。

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/json2.js"></script>
    <script src="/Scripts/bootstrap-3.2.0-dist/js/bootstrap.min.js"></script>
    <link href="~/Scripts/bootstrap-3.2.0-dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/fillform.js"></script>
    <title>Index</title>
    <script type="text/javascript">

        $(function () {
            $("#btntest").click(function () {
                $.post("/test2/getjsonstr", {}, function (data) {
                    fillckb("Teammate", data);
                    fillForm($("#fm1"), data);
                });
            });

        });
    </script>
</head>
<body>
    <div class="container"> 
        <form id="fm1" role="form" class="form-horizontal">
            <h2 class="h2 text-center">运动员资料</h2>
            <div class="form-group">
                <label class="control-label col-sm-2">Id:</label>
                <div class="col-sm-10">
                    <input type="text" name="Id" class="form-control" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2">Name</label>
                <div class="col-sm-10">
                    <input type="text" name="Name" class="form-control" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2">Birthday</label>
                <div class="col-sm-10">
                    <input type="text" name="Birthday" class="form-control" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2">Number</label>
                <div class="col-sm-10">
                    <select id="sel1" class="form-control" name="Number">
                        <option value="7" selected>7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2">Friends</label>
                <div class="col-sm-10">
                    <input type="checkbox" class="checkbox-inline" name="Friends" val="1" value="1">Saviola
                    <input type="checkbox" class="checkbox-inline" name="Friends" val="2" value="2">Batistuta
                    <input type="checkbox" class="checkbox-inline" name="Friends" val="3" value="3">Lopez
                    <input type="checkbox" class="checkbox-inline" name="Friends" val="4" value="4">Veron
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2">Teammate</label>
                <div class="col-sm-10">
                    <input type="checkbox" class="checkbox-inline" name="Teammate" val="1" value="1">Van Nistelrooy
                    <input type="checkbox" class="checkbox-inline" name="Teammate" val="2" value="2">Messi
                    <input type="checkbox" class="checkbox-inline" name="Teammate" val="3" value="3">Veron
                    <input type="checkbox" class="checkbox-inline" name="Teammate" val="4" value="4">Nedved
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2">Position</label>
                <div class="col-sm-10">
                    <input type="radio" class="radio-inline" name="Position" value="dc" val="dc" />后卫
                    <input type="radio" class="radio-inline" name="Position" value="mc" val="mc" />中场
                    <input type="radio" class="radio-inline" name="Position" value="fw" val="fw" />边锋
                    <input type="radio" class="radio-inline" name="Position" value="st" val="st" />射手
                </div>
            </div>
            <div class="text-center">
                <button type="button" class="btn btn-info col-sm-offset-2" id="btntest">确定</button>
            </div>
        </form>
    </div>
</body>
</html>
View Code

附赠json数据

{"Id":100,"Name":"Crespo","Birthday":"2014-08-19T16:06:01.0522081+08:00","Number":9,"Cotch":{"Id":1,"Name":"me"},"Friends":[{"Id":1,"Name":0},{"Id":3,"Name":0}],"Teammate":"3,4","Position":"st"}

最后帖张成功图片

 

总结:没什么难点,估计大家用点心都能做出来。对于类型的判断,写完后才觉得应该根据控件类型判断会更好,快下班了,回家再改吧。还有就是代码注释中$("[name=" + name + "][value=" + value + "]").attr("checked", "checked");这句话找不到具体的值,不知道是什么原因,还望大神指教。

转载于:https://www.cnblogs.com/woshiyfk/p/3922385.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值