JS常用方法总结,及jquery异步调用后台方法实例

查看字符串是否日期格式的函数,原创,很简单,而且大部分日期格式都支持,比如年月日,月日年等格式均可:

function isDate(val) {
return new Date(val) != "Invalid Date";
}

 

确定是日期格式后,比较两个字符串日期也很简单,直接转为日期比较即可,如下:

if(Date.parse(new Date(expireOrSignDate)) <= Date.parse(new Date()))

{...}

 

//前台接收get参数值

function getQueryString(name) {
            var queryStrings = window.location.search.split('&');
            for (var i = 0; i < queryStrings.length; i++) {
                if (queryStrings[i].indexOf(name + "=") != -1)
                    return queryStrings[i].substr(queryStrings[i].indexOf(name + "=") + name.length + 1, queryStrings[i].length);
            }
            return "";
        } 

 

 

//前台接收get参数值,这种实现也可以

function getQueryString(name) {
 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
 var r = window.location.search.substr(1).match(reg);
 if (r != null) return unescape(r[2]); return null;
}

 

把对象转换成string,此方法名称只能为parseString,要换名称就全部替换

parseString = function (obj) {
 switch (typeof (obj)) {
  case 'string':
   //return '"' + obj.replace(/(["file://])/g, '\\$1') + '"';
   return '"' + obj + '"';
  case 'array':
   return '[' + obj.map(parseString).join(',') + ']';
  case 'object':
   if (obj instanceof Array) {
    var strArr = [];
    var len = obj.length;
    for (var i = 0; i < len; i++) {
     strArr.push(parseString(obj[i]));
    }
    return '[' + strArr.join(',') + ']';
   } else if (obj == null) {
    return 'null';

   } else {
    var string = [];
    for (var property in obj) string.push(parseString(property) + ':' + parseString(obj[property]));
    return '{' + string.join(',') + '}';
   }
  case 'number':
   return obj;
  default:
   return obj;
 }
}

 

//利用option的text的值来默认选中某一项:

注意第一种方法有时不行,推荐第二种

1,$("#drpBrand").find("option[text='" + $("#hdBrand").val() + "']").attr("selected", true).change();
2,$("#drpBrand").find("option:contains('" + $("#hdBrand").val() + "')").attr("selected", true).change();

 

js中,按照值删除数组中的某个元素

Array.prototype.indexOf = function(val) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] == val) return i;
            }
            return -1;
        };
        Array.prototype.remove = function(val) {
            var index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        };

如:
        var array = [1, 2, 3, 4, 5];
        array.remove(3);

 

 

/// <summary>
  /// 复制对象
  /// </summary>
  /// <param name="target">目标对象</param>
  /// <param name="source">原始对象</param>
        private void TryUpdateModel(Object target, Object source)
        {
            var tprops = target.GetType().GetProperties();
            foreach (var prop in source.GetType().GetProperties())
            {
                var tprop = tprops.FirstOrDefault(p => p.Name.Equals(prop.Name));
                if (tprop == null) continue;
                tprop.SetValue(target, prop.GetValue(source, null), null);
            }
        }

 

/// <summary>
  /// 注册前台脚本
  /// </summary>
  /// <param name="scriptName">前台脚本变量名</param>
  /// <param name="scriptValue">脚本Json对象</param>
  protected void RegisterScript(string scriptName, object scriptValue)
  {
   var json = string.Format("{0}={1};", scriptName, JsonHelper.JsonSerialize(scriptValue));
   ClientScript.RegisterClientScriptBlock(typeof(string), scriptName + "json", json, true);
  }

 

//将[{name:'name1',value:'value1'}]转换为{'name1':'value1'}
function fixData(d) {
    var ndata = {};
    for (var i in d) {
        ndata[d[i].name] = d[i].value;
    }
    return ndata;

 

//限制某个文本框只能输入数字,无法输入字母

$('#dvMain').find(".memPhoneSearch input")
    .keypress(function (e) {
        var chars = "0123456789";
        var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
        return e.ctrlKey || e.metaKey || (chr < ' ' || chars.indexOf(chr) > -1);
    })

 

 

打开的pop窗口随着鼠标点击的dom元素而定位展示的js代码:

e是click事件,o是pop窗口的宽度或高度,

eventX = function (e, o) {
  e = e || window.event;
  o = o || 0;
  x = e.pageX || e.clientX + document.body.scroolLeft;
  return x + o > screen.availWidth ? screen.availWidth - o : x - o / 2 < 0 ? 0 : x - o / 2;
 }

 

eventY = function (e, o) {
  e = e || window.event;
  o = o || 0;
  alert('clientY = ' + e.clientY);
  y = e.pageY || e.clientY + document.body.scrollTop;
  return y + o > screen.availHeight ? screen.availHeight - o : y - o / 2 < 0 ? 0 : y - o / 2;
 }

 

 

一个button不在某个form内,点击该button时提交某个form的代码:

//e.preventDefault()可以不要

$("dvMain").find(".btnMemSearch").click(function (e) { e.preventDefault(), $(".memPhoneSearch form").submit() });

 

 

异步ajax方法封装(post传值,参数和返回值都是json形式):

注意一点:前端利用此方法异步调用后台WebService中的方法时,后台返回前台的Json字符串是有长度限制的,如果后台返回的Json字符串过长系统是会报错的,此时应在后台的web.config中的根节点下(即configuration节点内部)添加以下配置节点即可解决,当然具体返回的字符串的长度可以根据实际情况进行配置:

<system.web.extensions> 
    <scripting> 
      <webServices> 
        <jsonSerialization maxJsonLength="1024000000" /> 
      </webServices> 
    </scripting> 
</system.web.extensions>

 

ajax = function (uri, data, callback) {
 $.ajax({
  type: "post",
  cache: false,
  url: uri,
  data: data,
  dataType: "json",
  contentType: "application/json",
  success: callback,
  error: function (res) { alert(res) }
 });
}

使用此方法调用webservice后台方法 实例(注意 res.d):

前台:

ajax("/Web/WebService/CorseListService.asmx/GetCorseList", parseString({ CourseType: $("#ddlCourseType").val(), ClassID: $(this).val() }),
                    function (res) {
                        var data = eval("(" + res.d + ")");
                        //var data = $.parseJSON(res.d);
                        bindSelect("ddlCourse", data);
                        courseLoaded = true;
                    });

 

后台方法:

[WebMethod(EnableSession = true)]
    public string GetCorseList(string CourseType, string ClassID) {
        string result = "";
        string where = " DataState=1 and ClassTypeID = " + CourseType;
        if (ClassID != "-1")
        {
            List<ClassInfo> lc = ciMan.GetModelList("ID=" + ClassID);
            if (lc != null && lc.Count > 0)
            {
                where += "  and JobTypeID=" + lc[0].JobTypeId;
            }
        }
        List<NewAddCourse> adc = nacMan.GetModelList(where);
        result = JsonConvert.SerializeObject(adc.Select(o => new { Display = o.CourseName, Value = o.Id }).ToList());
        return result;
    }

 

传递对象的例子:

前台:

var item = {
                    Id: $("#hfItemID").val(),
                    SchoolId: $("#<%= ddlSchoolName.ClientID %>").val(),
                    ClassId: $("tr.trHide").is(":hidden") ? "-1" : $("#<%= ddlClass.ClientID %>").val(),
                    CourseId: $("#ddlCourse").val(),
                    TeacherId: $("tr.trHide").is(":hidden") ? "-1" : $("#<%= ddlTeacher.ClientID %>").val(),
                    Classroom: $("tr.trHide").is(":hidden") ? "-1" : $("#<%= ddlRoom.ClientID %>").val(),
                    CourseType: $("#ddlCourseType").val(),
                    StartTime: $("#txtStartDate").val(),
                    EndTime: $("#txtEndDate").val(),
                    StartTimeType: ($("#chkAllDay").attr("checked") ? 0 : $("#ddlStartType").val()),
                    EndTimeType: ($("#chkAllDay").attr("checked") ? 0 : $("#ddlEndType").val()),
                    ClassName: $("tr.trHide").is(":hidden") ? "-1" : $("#<%= ddlClass.ClientID %> option:selected").text(),
                    TeacherName: $("tr.trHide").is(":hidden") ? "-1" : $("#<%= ddlTeacher.ClientID %> option:selected").text(),
                    ClassroomName: $("tr.trHide").is(":hidden") ? "-1" : $("#<%= ddlRoom.ClientID %> option:selected").text(),
                    CourseName: $("#ddlCourse option:selected").text(),
                    Year: $("#hfYear").val()
                };

                ajax("/Web/WebService/CorseListService.asmx/ModifyCorse", parseString({ timeItem: item }),
                    function (res) {
                        var data = eval("(" + res.d + ")");
                        if (data.result == 1) {

                            $("#btnCommit").attr("disabled", false);
                            $("#btnCommit").show();

                            if (item.Id == 0) {
                                calendar.fullCalendar('renderEvent',
                                    data.item,
                                    true // make the event "stick"
                                );
                            }
                            else if (item.Id > 0)
                            {
                                var event = $('#calendar').fullCalendar('clientEvents', item.Id)[0];
                                //event = data.item;
                                //event.id = timeItem.Id;
                                event.title = data.item.title;
                                event.start = data.item.start;
                                event.end = data.item.end;
                                event.allDay = data.item.allDay;
                                event.courseType = data.item.courseType;
                                event.courseID = data.item.courseID;
                                event.classID = data.item.classID;
                                event.classRoomID = data.item.classRoomID;
                                event.teacherID = data.item.teacherID;
                                event.startType = data.item.startType;
                                event.endType = data.item.endType;
                                event.backgroundColor = data.item.backgroundColor;
                                event.year = data.item.year;
                                calendar.fullCalendar('updateEvent', event);
                            }

                            close();
                        }
                        else {
                            alert(data.item);
                        }
                    });

后台被调用方法:

[WebMethod(EnableSession = true)]
    public string ModifyCorse(NewTimetableMore timeItem)
    {
        UserInfo user = new UserInfo();
        if (Session["UserBase"] != null)
        {
            user = (UserInfo)Session["UserBase"];
        }
        string result = JsonConvert.SerializeObject(new { result = 0, item = "保存失败,请稍后重试!" });
        if (timeItem != null)
        {
            bool flag = false;
            CalendarItem calendar = new CalendarItem();
            timeItem.UpdateDate = DateTime.Now;
            timeItem.UpdateId = user.Id;
            //如果选择的是开始时间的上午和结束时间的下午就按照全天写入DB
            if (timeItem.StartTimeType == 1 && timeItem.EndTimeType == 2)
            {
                timeItem.StartTimeType = 0;
                timeItem.EndTimeType = 0;
            }
            //如果是新增记录,则使用当前年份
            if (timeItem.Id == 0)
            {
                timeItem.Year = timeItem.Year ?? System.DateTime.Now.Year;
            }
            timeItem.LengthTime = GetSingleCourseLengTime(timeItem.StartTime, timeItem.StartTimeType, timeItem.EndTime, timeItem.EndTimeType);
            //检查该课程的排课时长是否允许添加该排课
            double LeaveTime = nTm.GetCourseTimeLeaveTime(timeItem.SchoolId, (timeItem.Year ?? 0), timeItem.ClassId, timeItem.CourseId, timeItem.CourseType, timeItem.Id);
            if (LeaveTime < timeItem.LengthTime)
            {
                result = JsonConvert.SerializeObject(new { result = 0, item = (LeaveTime > 0 ? string.Format("该课程剩余时长为 {0} 天,请缩短排课天数!" , LeaveTime) : "该课程排课时间已满,无法再添加课程时长!") });
                return result;
            }

            if (timeItem.Id == 0)
            {
                timeItem.DataState = 1;
                timeItem.CreateDate = DateTime.Now;
                timeItem.CreateId = user.Id;
                NewTimetable DBTimeItem = new NewTimetable();
                TryUpdateModel(DBTimeItem, timeItem);
                int TimeID = nTm.Add(DBTimeItem);
                if (TimeID > 0)
                {
                    flag = true;
                    timeItem.Id = TimeID;
                }
            }
            else if (timeItem.Id > 0)
            {
                var item = nTm.GetModel(timeItem.Id);
                item.SchoolId = timeItem.SchoolId;
                item.CourseType = timeItem.CourseType;
                item.CourseId = timeItem.CourseId;
                item.ClassId = timeItem.ClassId;
                item.Classroom = timeItem.Classroom;
                item.TeacherId = timeItem.TeacherId;
                item.StartTime = timeItem.StartTime;
                item.EndTime = timeItem.EndTime;
                item.EndTimeType = timeItem.EndTimeType;
                item.StartTimeType = timeItem.StartTimeType;
                item.LengthTime = timeItem.LengthTime;
                item.UpdateDate = timeItem.UpdateDate;
                item.UpdateId = timeItem.UpdateId;
                flag = nTm.Update(item);
            }

            if (flag)
            {
                calendar.id = timeItem.Id;
                calendar.title = GetTitleMoreInfo(timeItem);
                calendar.start = timeItem.StartTime.ToString("yyyy-MM-dd");
                calendar.end = timeItem.EndTime.ToString("yyyy-MM-dd");
                //calendar.allDay = (timeItem.StartTimeType == 0 && timeItem.EndTimeType == 0);
                calendar.allDay = true;
                calendar.courseType = timeItem.CourseType;
                calendar.courseID = timeItem.CourseId;
                calendar.classID = timeItem.ClassId;
                calendar.classRoomID = timeItem.Classroom;
                calendar.teacherID = timeItem.TeacherId;
                calendar.startType = timeItem.StartTimeType;
                calendar.endType = timeItem.EndTimeType;
                calendar.backgroundColor=BackGroundColorList[timeItem.CourseType - 1];
                calendar.year = timeItem.Year;
                result = JsonConvert.SerializeObject(new { result = 1, item = calendar });
            }
        }
        return result;
    }

 

向后台方法传递参数是数组时的实例:

前台:

相当于调用时参数形式为:CustomerID=1001&CustomerID=1002&CustomerID=1003这种形式可以调用后台参数为string[] CustomerID的参数
此处前台之所以用escape方法,是因为Content参数是html代码,后台接受时用Content = Server.UrlDecode(Content);解密获取参数。

var val = [];
                $(".scrollBox2b li.cur").each(function () {
                    //$(this).hasClass("cur") && val.push($(this).attr("data-cid"));
                    val.push($(this).attr("data-cid"));
                })

                if (val.length > 0) {
                    $.get("@Url.Action("MailContentMode")", function (data) {
                        var MailContent = data.replace("$EmailContent$", $("#calcResult").html());
                        var param = "CustomerID=" + val.join("&CustomerID=") + "&Subject=" + escape(escape("房贷计算结果")) + "&Content=" + escape(escape(MailContent));
                        $.post("@Url.Action("SendEmail")", param, function (data) {
                            alert(data.msg);
                        })
                    })
                }
                else {
                    alert("请至少选择一个客户!");
                }

后台被调方法:

public ActionResult SendEmail(Guid[] CustomerID, string Subject, string Content)
        {
            string Msg = "发送失败,请稍后重试!";
            int result = 0;
            Subject = Server.UrlDecode(Subject);
            Content = Server.UrlDecode(Content);
   var Customers = new CustomerService().Filter(p => CustomerID.Contains(p.ID)).ToList();
            Customers = Customers.Where(p=>p.Email.IsEmail()).ToList();
            var mail = new FocusEmail
            {
                Subject = Subject,
                Body = Content,
                IsBodyHtml = true
            };
            List<FocusReceiver> Receivers=new List<FocusReceiver>();
            foreach (var cus in Customers)
            {
                Receivers.Add(
                    new FocusReceiver
                    {
                        Email = cus.Email,
                        FullName = cus.Name
                    }
                );
            }
            if (Receivers.Count() > 0)
            {
                if (Email.Send(mail, Receivers.ToArray()).ToLower() == "success")
                {
                    Msg = "发送成功";
                    result = 1;
                }
                else
                {
                    Msg = "发送失败,请稍后重试!";
                    result = -1;
                }
            }
            else
            {
                Msg = "发送失败,没有有效的邮箱";
                result = -2;
            }
            return Json(new { result = result, msg=Msg });
        }

 

再如:

前台:
var cid = [], rid = [], fid = $("#FID").val();
  $(".data_distribution_table tbody :checkbox[name=cid]:checked").each(function () { cid.push($(this).val()) })
  $(".label_w :checkbox[name=rid]:checked").each(function () { rid.push($(this).val()) })
  if (!$(".table_d").hasClass("disabled")) {
   $.post("@Url.Action("Alloc")", "cid=" + cid.join("&cid=") + "&rid=" + rid.join("&rid="), function (res) {
    alertE(res.msg);
   })
  }

后台:
public ActionResult Alloc(Guid[] cid, Guid[] rid)
  {
   var cl = cid.Length;//客户数
   var rl = rid.Length;//顾问数
   var size = cl / rl;//每人分配数
   var lft = cl % rl;//剩余未分配数
   var offset = 0;
   var ser = new CustomerService();
   var iser = new ImportCustomerService();
   for (var i = 0; i < rl; i++)
   {
    List<Guid> lcid = new List<Guid>(size);
    for (var j = 0; j < size; j++)
    {
     var idx = i * size + j + offset;
     if (cl > idx) lcid.Add(cid[idx]);
    }
    if (i < lft)
    {
     var idx = (i + 1) * size + offset;
     offset++;
     if (cl > idx) lcid.Add(cid[idx]);
    }
    var trid = rid[i];
    ser.Update(p => lcid.Contains(p.ID), p => new Customer { RealtorID = trid });
   }
   foreach (var item in iser.Filter(p => p.Customer.Any(x => cid.Contains(x.ID))).Select(p => new { p.ID, Cnt = p.Customer.Count(x => x.RealtorID.HasValue) }).ToList())
   {
    var iid = item.ID;
    var icnt = item.Cnt;
    iser.Update(p => p.ID == iid, p => new ImportCustomer { DistributionRate = icnt });
   }
   return Json(new { success = true, msg = "分配成功" }, JsonRequestBehavior.AllowGet);
  }

 


js绑定select:

bindSelect = function (selectid, jsondata) {
    addSelectNullItem(selectid);
    for (var item in jsondata) {
        addSelectItem(selectid, jsondata[item].Display, jsondata[item].Value);
    }
}

 

addSelectItem = function (selectid, text, value) {
    $("#" + selectid + "").append("<option value='" + value + "'>" + text + "</option>");
}

addSelectNullItem = function (selectid) {
    $("#" + selectid + "").empty();
    $("#" + selectid + "").append("<option value='-1'>--请选择--</option>");
}

//加载类别信息
    function tmpSmsLoadCategory(data) {
        var c = $('#selectID').html('');
        for (var i in data) {
            $('<option></option>').text(data[i].ExtValue).val(data[i].ExtCode).appendTo(c);
        }
    }

 

 

// 对Date的扩展,将 Date 转化为指定格式的String  
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,  
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)  
// 例子:  
// (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423  
// (new Date()).format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18  
Date.prototype.format = function (fmt) { //author: meizz  
 var o = {
  "M+": this.getMonth() + 1,                 //月份  
  "d+": this.getDate(),                    //日  
  "h+": this.getHours(),                   //小时  
  "m+": this.getMinutes(),                 //分  
  "s+": this.getSeconds(),                 //秒  
  "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
  "S": this.getMilliseconds()             //毫秒  
 };
 if (/(y+)/.test(fmt))
  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt))
   fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 return fmt;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值