首页 > 代码库 > jQuery通过ajax获得后台json数据给form表单赋值
jQuery通过ajax获得后台json数据给form表单赋值
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=http://www.mamicode.com/"1">门店>总结的方法:
页面调用:
<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); }); </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表单中了。看了之后有木有感觉很有爱啊。
jQuery通过ajax获得后台json数据给form表单赋值
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。