_xkoko
COCO 很懒 什么都没留下......
 1 //自动获取页面控件值
 2 
 3 function GetWebControls(element) {
 4 var reVal = "";
 5 
 6 $(element).find('input,select,textarea').each(function (r) {
 7 var id = $(this).attr('id');
 8 var value = $(this).val();
 9 var type = $(this).attr('type');
10 switch (type) {
11 case "checkbox":
12 if ($(this).is(':checked')) {
13 reVal += '"' + id + '"' + ':' + '"1",';
14 } else {
15 reVal += '"' + id + '"' + ':' + '"0",';
16 }
17 break;
18 default:
19 reVal += '"' + id + '"' + ':' + '"' + $.trim(value) + '",';
20 break;
21 }
22 });
23 /* 
24 将回车字符替换成\\n
25 */
26 reVal = reVal.replace(/\n/g, " ");
27 reVal = reVal.substr(0, reVal.length - 1);
28 return jQuery.parseJSON('{' + reVal + '}');
29 
30 }
 1 //自动给控件赋值
 2 function SetWebControls(data) {
 3 for (var key in data) {
 4 var id = $('#' + key);
 5 var value = $.trim(data[key]).replace(" ", "");
 6 var type = id.attr('type');
 7 switch (type) {
 8 case "checkbox":
 9 if (value == 1) {
10 id.attr("checked", 'checked');
11 } else {
12 id.removeAttr("checked");
13 }
14 break;
15 default:
16 id.val(value);
17 break;
18 }
19 }
20 }
 1 /* 请求Ajax 带返回值*/
 2 
 3 function postAjax(url, parm, callBack) {
 4 $.ajax({
 5 type: 'post',
 6 contentType: 'application/json',
 7 dataType: 'json',
 8 url: url,
 9 data: JSON.stringify(parm),
10 cache: false,
11 async: false,
12 success: function (msg) {
13 callBack(msg);
14 }
15 });
16 }

========================分割线 以上是js通用方法,以下是调用==========================

 1 //添加
 2 function add() {
 3 var postData = GetWebControls("#fm");          // 获取post方法from表单的内容 
 4 postAjax("../url", postData, function (data) {      // url:后台控制器的url  postData:需要提交json格式的参数  可为null  或者自定义 var postData = { "id": id };
 5 
 6 if (data != null && data != "") {
 7 alert(data);
 8 }
 9 else {
10 //  doing something...
11 }
12 });
13 }
14 
15 //更新
16 
17 function updateData(id) {
18 var postData = { "id": id };
19 postAjax("../url", postData, function (data) {
20 var results = eval(data); 
21 var result = results[0];
22 if (result != null && result != "") {
23 SetWebControls(result);  // 自动给控件赋值
24 }
25 else {
26 //doing something ...
27 }
28 });
29 }

 

posted on 2018-01-18 14:32  _xkoko  阅读(692)  评论(0)    收藏  举报