jQuery通过ajax获得后台json数据给form表单赋值

来源:互联网 发布:崩坏3淘宝 编辑:程序博客网 时间:2024/05/16 17:49

jQuery提供了load方法可以将数据加载到页面form表单中,但有时候我需要获取后台json数据中某个值时,又需要赋值整个form表单,load方法没有回调函数所以就不行了,如果用ajax调用的话,获得后台json数据后把json数据分析出来在一个个的赋值到form表单的每个文本框中,这样未免太过复杂和太多代码,所以我根据了一些大神的回答,总结了一个很好用的jQuery函数。

jQuery-load方法调用:

$('#form').form('load',URL);


页面表单:

<span style="font-size:18px;"><form id="form" action="system/info/area_operate.html" method="post" class="default">    <input type="text" name="area_name" readOnly/>       <input type="text" name="name"/><select id="type" name="type" ><option value="1">门店</option><option value="2">总部</option></select>           <textarea class="easyui-validatebox" name="remark" cols="40" rows="5" required="false"></textarea></form></span>

总结的方法:

页面调用:

<span style="font-size:18px;"><script><span style="white-space:pre"></span>$.getJSON(URL,param,function(data){<span style="white-space:pre"></span>alert(data.type);<span style="white-space:pre"></span>$("form").setForm(data);//将ajax获得的数据设值到form表单中取});</script></span>

把下面这段代码放入到jQuery中取

<span style="font-size:18px;">$.fn.setForm = function(jsonValue) {    alert("setForm");    var obj=this;    $.each(jsonValue, function (name, ival) {    var $oinput = obj.find("input:[name=" + name + "]");     if ($oinput.attr("type")== "radio" || $oinput.attr("type")== "checkbox"){     $oinput.each(function(){                 if(Object.prototype.toString.apply(ival) == '[object Array]'){//是复选框,并且是数组                      for(var i=0;i<ival.length;i++){                          if($(this).val()==ival[i])                             $(this).attr("checked", "checked");                      }      }else{                     if($(this).val()==ival)                        $(this).attr("checked", "checked");                 }             });    }else if($oinput.attr("type")== "textarea"){//多行文本框    obj.find("[name="+name+"]").html(ival);    }else{             obj.find("[name="+name+"]").val(ival);         }   });};</span>

注意页面启动ajax方法,然后这样就可以通过ajax拿到自己想要的值,又可以将值全部赋值到form表单中了。

看了之后有木有感觉很有爱啊。生气







2 0
原创粉丝点击