您的位置:首页 > Web前端 > JavaScript

common.js

2015-12-10 11:26 603 查看
/**
* Created by bing on 2015/12/3.
*/
/*获取聊天时的变量*/
var tid;
var oppId;

function setCurrPage(){             //
var currPage = window.location.href;
if(currPage.indexOf("login.html")==-1){                 //判断login.html首次出现的位置
var t=currPage.substring(0,currPage.lastIndexOf("/"));          //截取最后出现“/”之间的所有字符
currPage=currPage.substring(t.lastIndexOf("/"),currPage.length);        //截取t中最后一次出现“/”的之间长度
localStorage.currPage=".."+currPage;                                //".."+截取t中最后一次出现“/”的之间长度
}
}
setCurrPage();
//加载数据时先判断是否登录
$(function(){
if(localStorage.shstoken == undefined || localStorage.shstoken == ""){
var url = window.location.href;
if(url.indexOf("SymptomCheck")==-1 && url.indexOf("login.html")==-1 && (url.indexOf("ExpertOnline")==-1) && (url.indexOf("DoctorDetails")==-1)&& (url.indexOf("SymptomList")==-1)&& (url.indexOf("Guide.html")==-1)){
openLogin();
return false;
}
}
if(!loginIs())return false;
loadBefore();
loadDivDatas("rows0",true);
loadDivDatas("rows1",true);
loadDivDatas("rows2",true);
loadDivDatas("rows3",true);
loadDivDatas("rows0",false);
loadDivDatas("rows1",false);
loadDivDatas("rows2",false);

loadAfter();
});

//异步取数据,调用服务的action,通过&传参数

function doService(action,paras){
try {
var value="";
// var url = "/web/server.aspx?action=" + action + "&" + encodeURI(paras);
var url = paras;
var userId = getUserId(); //  getCookieUserId();
url += '&userId=' + userId;

var strJson='{';
var paraList=url.split("&");
for(var i=0;i<paraList.length;i++)
{
var paraValue=paraList[i].split("=");
strJson+='"'+paraValue[0]+'":"'+paraValue[1]+'",';
}
if(strJson.length>1)strJson=strJson.substring(0,strJson.length-1);
strJson+='}';

var formData=JSON.parse( strJson );

if(formData.url==null || formData.url=="")
{
alert("请求地址为空!");
return null;
}
console.log("请求地址:"+formData.url);
if(formData.secretKey != undefined){
var temp = "SHSnosecurityV2yss"+formData.secretKey;
formData.secretKey = $.md5(temp);
}
if(clientStr == undefined){
var clientStr = localStorage.client;
}
var headers = {
"shstoken": localStorage.shstoken,
"client": localStorage.client
}
if(action=="upFile")
{
headers = {
"Content-Type":"multipart/form-data",
"shstoken": localStorage.shstoken,
"client": localStorage.client
}
}
$.ajaxSetup({ async: false });
$.ajax({
url:"/"+formData.url,
type :'POST',
data : formData,
dataType: 'json',
headers: headers,
success : function(responseStr) {
console.log("成功:"+JSON.stringify(responseStr));
if(JSON.stringify(responseStr) == 2){
openLogin();
}
if(JSON.stringify(responseStr) == 1){
isLogin();
}
var str=formData.url.replace(/[0-9]+/g,"*");
if(str == "healthtree-patient/doctor/infoWithKey/*.json" || str == "healthtree-patient/doctor/info/*.json"){
var Closetype = "";
for(var a = 0;a<3;a++){
if(responseStr.data.meal[a] != undefined){
Closetype = Closetype+responseStr.data.meal[a].type;
}else{
if(!checkab(Closetype,0)){
var obj = {
"id": "",
"type": 0,
"markClose": 0,
"unit":"",
"vipPrice": "",
"price": ""
};//定义了一个对象
responseStr.data.meal.push(obj);
Closetype = Closetype+"0"
}
if(!checkab(Closetype,1)){
var obj = {
"id": "",
"type": 1,
"markClose": 0,
"unit":"",
"vipPrice": "",
"price": ""
};//定义了一个对象
responseStr.data.meal.push(obj);
Closetype = Closetype+"1"
}
if(!checkab(Closetype,2)){
var obj = {
"id": "",
"type": 2,
"markClose": 0,
"unit":"",
"vipPrice": "",
"price": ""
};//定义了一个对象
responseStr.data.meal.push(obj);
Closetype = Closetype+"2"
}
}
}

if(responseStr.data.vip == 0){
for(var i = 0 ;i<responseStr.data.meal.length;i++){
responseStr.data.meal[i].vipPrice = responseStr.data.meal[i].price;
}
}else{
for(var i = 0 ;i<responseStr.data.meal.length;i++){
responseStr.data.meal[i].price = responseStr.data.meal[i].vipPrice;
}
}
for(var j=0;j<responseStr.data.meal.length;j++){
if(responseStr.data.meal[j].type == 2){

22454
if(responseStr.data.meal[j].markClosed != 2){
responseStr.data.timeAnswer = "无";
}else{
if(responseStr.data.timeAnswer == ""){
responseStr.data.timeAnswer = "无";
}else if(responseStr.data.timeAnswer < 20){
responseStr.data.timeAnswer = "20秒";
}else if(responseStr.data.timeAnswer > 600){
responseStr.data.timeAnswer = "600秒";
}else{
responseStr.data.timeAnswer= responseStr.data.timeAnswer+"秒";
}
}
}else{

}
}
value = responseStr;
}else{
value=responseStr;
}
},
error : function(responseStr) {
console.log("失败:"+JSON.stringify(responseStr));
value=responseStr;
}
});
return value;

}
catch (e) {
console.log(e.message);
$.messager.alert("提示", "找不到这个方法!", "info");
}
}

function openLogin(){                   //跳到登录界面
localStorage.shstoken="";
alert("您还没有登录,请登录后再操作");
window.location = '../Scancode/login.html?currPage=' + localStorage.currPage;
}
function isLogin(){                     //判断是否登录
if(localStorage.shstoken!=undefined && localStorage.shstoken!=""){
return true;
}else{
alert("您还没有登录,请登录后再操作");
//        currPage = window.location.href;
//        var t=currPage.substring(0,currPage.lastIndexOf("/"))
//        currPage=currPage.substring(t.lastIndexOf("/"),currPage.length);
//        currPage=".."+currPage;
//        currPage = "../secondRoom/twoRoom.html";
window.location = '../Scancode/login.html?currPage=' + localStorage.currPage;
return false;
}
}

//图片上传
function upLoadImg(fileId){             //图片的id(fileId)
var forData=new FormData();
forData.append("file",$("#"+fileId)[0].files[0]);           //上传图片(“file类型”,得到图片id从0开始排序,)
var uploadUrl="/healthtree-patient/resource/uploadimg.json";
$.ajaxStup({async:false});
$.ajax({
header:{
"shstoken":localStorage.shstoke,
"client":clientStr
},
url:uploadUrl,
type:'POST',
data:forData,
contentType:false,
processType:false,
dataType:'json',
success:function(responseStr){
// console.log(JSON.stringify(responseStr));
value = responseStr;
},
error:function(responseStr){
// console.log("error"+JSON.stringify(responseStr));
value = responseStr;
}
});
return value.data;
}

//上传文件
function upLoadFile(uploadUrl,fileId,caseId,clientid,type){
var formData = new FormData();
formData.append("file",$("#"+fileId)[0].files[0]);
formData.append("caseId",caseId);
formData.append("clientid",clientid);
formData.append("type",type);
var value="";
$.ajax({
headers:{
"shstoken":localStorage.shstoken,
"client":clientStr
},
url:uploadUrl,
type:'POST',
data:formData,
processType:false,
contentType:false,
dataType:'json',
success : function(responseStr) {
console.log(JSON.stringify(responseStr));
value=responseStr;

},
error : function(responseStr) {
console.log("失败:" + JSON.stringify(responseStr));
value=responseStr;
}
});
return value;
}

//调用doService,添加到页面
function updateRowData(row){return row;}
function loginIs(){return true;}
function loadBefore(){$("mask1").css("display","");return true} //上传之前得到mask1隐藏
function loadAfter(){return true;}
function loadRowAfter(datas){return true;}//加载行之后
function loadSubRowAfter(divId,datas){ return true;}
function loadSubRow0After(divId,datas){return true;}

//加载div中的数据,并判断isRows是否加载多行
function loadDivData(divId,isRows){
var divObj = $("#"+divId);
if(divObj != null && divObj.length ==1){
var keys = divObj.attr("keys");
var id = getUrlKeyValue("id");
if(id !=""){
keys = keys.replace(/@id@/g,id);
}
var name =getUrlKeyValue("name");
if(name !=""){
name=decodeURI(name);
keys=keys.replace(/@name@/g, name);
}
var func = "getRows";                   //定义一个变量,命名为“getRows”,判断是否是为多行,
if(!isRows){
func="getRows";
}
var info = doService(func,keys);                //单层数据时用getRows命名取数据

if(info.errcode !=0){
if(info.errmsg == "没有权限"){
alert("登录失败,请重新登陆");
window.location.href="../Scancode/login.html";
}
replaceEmptyString(divId);                  //替换空字符串
}else{
if(isRows){
loadRows(divId,info.data);
}else{
loadRow(divId,info.data);
}
}

}
}

//多行数据集合写入div
function loadRows(div, rows, div_templet){              //(div,数据,div模版)
var divs="";
if(div_templet !=undefined)divs = $("#"+div).html();
var rows00key = "";
var rows00=$("#rows00");
if(rows00.length ==1){
rows00key = rows00.attr("keys");
}
var divHtml00 = rows00.html();
if(rows !=""){
if(rows.list !=undefined){
rows =rows.list;
}
if(rows.list!=null)rows=rows.list;
$.each(rows,function(n,row){
var divHtml = $("#"+div).html();
if(div_templet!=undefined)divHtml = $("#"+div_templet).html();
divHtml = divHtml.replace("@index@",n);    //替换行索引值0,1,2,3,4.........
for(var key in row){
var value = row[key];
divHtml = divHtml.myReplace("@"+key+"@" , value);
if(key == rows00Key && rows00Key !=""){                 //处理子集合
var div00 = loadsubDiv("rows00",row[rows00Key]);
divHtml = divHtml.replace($("#rows00").html(),div00);       //子集合的数量
var div01 = loadsubDiv("rows01",row[rows00Key]);
divHtml = divHtml.replace($("#rows01").html(),div01);       //div下面的的子集合

}
}
divHtml = execFunc(divHtml);            //执行一个方法并替换其中的参数值
divs += divHtml;
});

}
try{divs = decodeURI(divs)
}catch(e){}
$("#"+div).html(divs);
}

//装载子div
function loadsubDiv(div,dataRows){
var divs = "";
var obj = $("#"+div);
var divHtml = obj.html();
if(divHtml == undefined) return;
if(typeof (dataRows) == "string"){
dataRows = JSON.parse(dataRows);   //可能是单行数据
for(var key in dataRows){
var value = dataRows[key];
divHtml = divHtml.replace("@" +key+"@");
}
loadSubRowAfter(divHtml,dataRows);
divs+=divHtml
}
else{
$.each(dataRows,function(n,row){
var divHtml = obj.html();
for(var key in row){
var value = row[key];
divHtml = divHtml.replace("@"+key+"@");
}
divs+=divHtml;
});
}
return divs;
}

//把数据行绑定表单
function loadFrom(fromId,row){
if(row ==null){
return;
}
fromId.form("load",row);
}

//把数据绑定表单    
function loadRow(div,row){
row = updateRowData(row);
var row00Key = ""; //确实是否有子div需要绑定数据
var row00 = $("#row00");
if (row00.length == 1) {
row00Key = row00.attr("keys");
}
var divHtml00 = row00.html();
var divHtml = $("#" + div).html();
for (var key in row) {
var value = row[key];
divHtml = divHtml.myReplace("@" + key + "@", value);
if (key == row00Key && row00Key != "")//处理子集合
{
var div00 = loadSubRow0After(divHtml00, row[row00Key])
// var div00 = loadsubDiv('row00', row[row00Key]);
divHtml = divHtml.replace(divHtml00, div00);
// execFunc(divHtml);
//            var div01 = loadsubDiv('rows01', row[rows00Key]);
//            divHtml = divHtml.replace($("#rows01").html(), div01);    //子集合的个数有多少?
// execFunc(divHtml);
//loadRowAfter();
}
}
// divHtml= execFunc(divHtml);
$("#" + div).html(divHtml);
}

//替换空字符串 如:@name@=''
function replaceEmptyString(div){                       //传进id参数
var divHtml = $("#"+div).html();
while(true){
var key = divHtml.getBetween("@","@");
if(key == "")break;
divHtml = divHtml.replace("@"+key+"@","");
}
$("#"+div).html(divHtml);
$("#"+div).html("");
}

//执行一个方法,并且替换参数值
function execFuncs(divHtml){
var divHtmlNew = divHtml;
while(true){
var divHtmlTemp = execFuncs(divHtmlNew);
if(divHtmlTemp == "")
return divHtmlNew;
else
divHtmlNew = divHtmlTemp;
}
return divHtmlNew;
}

//执行一个方法并替换值 如:[getLocalTime:@sentTime@]
function execFunc(divHtml){
var func = divHtml.getBetween("[","]");        //获取方法名
if(func !=undefined && func !="" && func.indexOf(":")>0){
var a = func.split(":");
var funName = a[0];                     //获得第一个参数
var para0 = a[1];                       //获得第二个参数
var funObj = eval(funName);             //字符串转化为对象
var value = funObj(para0);              //执行方法funName
divHtml = divHtml.replace("["+func+"]",value);
return divHtml;
}
return "";                                  //没有方法直接返回为空
}

//传参接口
function formSubmit(){
var result;
var info = "true";
if(info == "true"){
var frm = $("#frmEdit0");
var paras = frm.attr("keys");
frm.form('submit',{
url:"/web/server.aspx?action=saveForm&"+paras,
onSubmit:function(){                                //提交之前触发该事件,如果返回false则组织提交
return $(this).form("validate");
},
async:true,
success:function(info){
result = ""+info;
return result;
}
})
}
}

//获取key值,在string原型上增加一个getUrlValue方法
String.prototype.getUrlValue = function(key){
url0 = this.getAfter("?");                          //获取字符串?的之前的所有的字符
if(url0 == "")                                     //判断url0是否为空
url = this;
value = "";
$.each(url0.split("&"),function(n,me){
var a = me.aplit("=");
if(a[0].trim().toLowerCase() == key.trim().toLowerCase()){
value = a[1];
return true;
}
});
return value;
}
function getUrlKeyValue(key){
var url = document.location.search.trim("?");             //查找截取以问号结尾和以问号开始的中间部分,并且去除问号
// var url = document.location.search.trimEnd("?").trimStart("?);   去除首尾问号
return url.getUrlValue(key);
}

//trimEnd,trimStart,trim的原型
String.prototype.trimStart = function(trimStr){
if(!trimStr){return this;}
var temp = this;
while(true){
if(temp.substr(0,trimStr.length)!=trimStr){
break;
}
temp = temp.substr(trimStr.length);
}
return temp;
};
String.prototype.trimEnd = function(trimStr){
if(!trimStr){return this;}
var temp = this;
while(true){
if(temp.substr(temp.length-trimStr.length,trimStr.length)!=trimStr){
break;
}
temp = temp.substr(0,temp.length-trimStr.length);
}
return temp;
};
String.prototype.trim = function(trimStr){
var temp = trimStr;
if(!trimStr){temp=" ";}
return this.trimStart(temp).trimEnd(temp);
};

//截取某个字符的前半部分
String.prototype.getBefore = function(str){
var  index = this.indexOf(str);
if(index < 0) return "";
var  str0 = this.substr(0, index);
return str0;
}
//截取某个字符的后半部分
String.prototype.getAfter = function(str){
var   index = this.indexOf(str);
if(index < 0) return "";
var str0 = this.substr(index + subStr.length);
return str0;
}

//获取字符的中间部分
String.prototype.getBetween = function(strStart,strEnd){
//var indexStart = this.indexOf(strStart);
//var indexEnd =this.indexOf(strEnd);
//var url0 = this.substring(indexStart,indexEnd);
//return url0;
//方法2
try{
newStr = this.getAfter(strStart);
if(newStr == "") return "";
newStr = newStr.getBefore(strEnd);
return newStr;
}catch(e){
alert(e);
return "";
}
}

//获取url的参数
function getUrlKey(paras){
var url = location.href;
//如 url = "www.baidu.com?id="+id
var paraString = url.substring(url.indexOf("?") + 1,url.length).split("&");         //得到url?首次出现的位置,
var paraObj = {};
for(i=0; j = paraString[i];i++){
paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length)
}
var returnValue = paraObj[paras.toLowerCase()];
if(typeof (returnValue) == "undefined"){
return "";
}else{
return returnValue;
}
}

//获取时间
function getTimes(){
var data = new Date();
var date = data.getTime();              //获取到当前的时间戳
//return getLocalTime(date);
var myDate = new Date(parseInt(date));

var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
var date = year + '年' + month + '月' + day + '日';

var hours = myDate.getHours();
var minutes = myDate.getMinutes();
var second = myDate.getSeconds();
var time = hours + ':' + minutes + ':' + second;
return date + " " + time;
}
/********cookie的操作*******/
//创建cookie
function setCookie(name, value)
{
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var LargeExpDate = new Date ();
if(expires!=null)
{
LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));
}
document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString()));
}
//读取cookie
function getCookie(Name)
{
var search = Name + "=";
if(document.cookie.length > 0)
{
offset = document.cookie.indexOf(search)
if(offset != -1)
{
offset += search.length
end = document.cookie.indexOf(";", offset)
if(end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
else return ""
}
}
//删除cookie
function deleteCookie(name)
{
var expdate = new Date();
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
setCookie(name, "", expdate);
}

/**[font=宋体][size=2]设值
localStorage.hello = 'world';
localStorage.zhangsan = 'lisi';
//取值:
var value_of_hello_in_localStorage = localStorage.hello;
var value_of_zhangsan_in_localStorage = localStorage.zhangsan
[/size][/font]

//设值:
localStorage.setItem("hello", "world");
localStorage.setItem("zhangsan", "lisi");
//取值:
localStorage.getItem("hello");
localStorage.getItem("zhangsan");

*/
/****H5本地存储设置键值和读取键值*****/
function saveUserId(name,value){
localStorage.clear();
//设置一个值
localStorage.setItem("userId",value);
}
function getUserId(name){
localStorage.getItem(name);
}

/******例子:获取用户信息********/
function getUserInfo(){
var keys = 'url=healthtree-patient/patient/get.json';
var lists = doService('getRow' , keys).data;
// lists = JSON.parse(lists);
return lists;
}
//获取医生列表
function getDoctors(doctorid){
var keys = 'url=healthtree-patient/doctor/info/{doctorid}.json';
keys = keys.replace('{doctorid}',doctorid);
var lists = doService('getRow',keys);
return lists;
}
//获取医生问题列表
function getProDoctor(problemId){
var keys = 'url=healthtree-patient/problem/get/doctor/{problemId}.json';
keys = keys.replace('{problemId}',problemId);
var lists = doService('getRows',keys);
return lists;
}

//图片错误处理
function imgError(){
$(".myHeadImage").bind('error', function() {
this.src="../images/huan_zhe_head.png";
});
$(".doctorHeadImage").bind('error', function() {
this.src="../images/doctordefaultimg.png";
});
}

//获取聊天记录
function getChatRecord(userId,page,type){
var keys = 'url=healthtree-patient/chat/getMessageHistory/'+tid+'.json';
var a = doService('getRows',keys + "&oppId="+tid+"&type="+type).data;
return a;
}

//得到剩余数
function getUserNum(userId,type){
var keys = 'url=healthtree-patient/chat/getMsgCount.json';
var paras = keys +"&type="+type;
if(tid !=""){
paras+="&tId="+tid;
if(oppId =="") oppId = tid;
}
paras +="&oppId="+oppId;
var a = doService('getRow' , paras).data;
return a;
}

//获取问题聊天记录
function getProChatRecord(userId,pageNum,type,pid){
var para ="type=1&pid="+pid+"&pageNum="+pageNum+"&pageSize=10";
para +='&url=healthtree-patient/problem/get/info/quality/'+pageNum+'/10.json';
var a = doService('getChatRecord',para).data;
return a;
}
//聊天记录保存到服务器
function saveChat1(dataObj){
var a = JSON.stringify(dataObj);
var a = doService('saveChat','url='+a);
}
function saveChat(dataObj){
$.ajaxSetup({async:false});
console.log("保存参数如下:");
console.log("url:/healthtree-patinet/chat/saveChat.json");
console.log("headers:shstoke"+localStorage.shstoken);
console.log("headers:client"+clientStr);
console.log("参数:"+JSON.stringify(dataObj));
$.ajax({
url:'/healthtree-patient/chat/saveChat.json',
type:'post',
dataType:'json',
headers:{
"shstoken":localStorage.shstoken,
"client":localStorage.clientStr
},
data:dataObj,
success:function(data){
console.log("返回数据:"+JSON.stringify(data));
},
error:function(data){
console.log("错误:"+JSON.stringify(data));
}
});
}

//获取字符串长度
function getStringLength(str){
var realLength = 0, len = str.length, charCode = -1;
for(var i=0;i<len;i++){
charCode = str.charCode(i);
if(charCode >=0 && charCode<=128) realLength +=1;
else
realLength +=2;
}
return realLength;
}

//
var g = this,
doc = this.document,
w = doc.documentElement.clientWidth || doc.body.clientWidth,
h = doc.documentElement.clientHeight || doc.body.clientHeight,
jQ = this.jQuery,
gPB = g.getPopBox,
Util = {
showMessage: function (message, fn) {
gPB("JavaScript提醒", message, function () {

}, function () {
fn();
}, false, {
fDW: 300,
fDH: 200,
cH: 100,
cLH: 20
});
},
uuid: function () {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''),
uuid = new g.Array(36), rnd = 0, r;
for (var i = 0; i < 36; i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
uuid[i] = '-';
} else if (i == 14) {
uuid[i] = '4';
} else {
if (rnd <= 0x02) rnd = 0x2000000 + (g.Math.random() * 0x1000000) | 0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
},
timedate: function () {
var date = new Date();
var dateNum = date.getTime();
return dateNum;
},
formatDate: function (time, split1, split2, type) {
var t = new g.Date(time),
year = t.getFullYear(),
month = t.getMonth() + 1,
dt = t.getDate(),
hour = t.getHours(),
minute = t.getMinutes(),
second = t.getSeconds(),
stamp = '';
if (hour <= 3) {
stamp = " 凌晨";
} else if ((hour > 3) && (hour <= 7)) {
stamp = " 清晨";
} else if ((hour > 7) && (hour <= 11)) {
stamp = " 上午";
} else if ((hour > 11) && (hour <= 17)) {
stamp = " 下午";
} else if ((hour > 17) && (hour <= 24)) {
stamp = " 晚上";
}
((month < 10) ? (month = "0" + month) : (month)) && ((dt < 10) ? (dt = "0" + dt) : (dt)) && ((hour < 10) ? (hour = "0" + hour) : (hour)) && ((minute < 10) ? (minute = "0" + minute) : (minute)) && ((second < 10) ? (second = "0" + second) : (second));
switch (true) {
case (type === "all"):
return year + split1 + month + split1 + dt + stamp + hour + split2 + minute + split2 + second;
break;
case (type === "day"):
return dt;
break;
case (type === "hour"):
return hour;
break;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: