forked from boypt/stock-viewer
-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.js
66 lines (60 loc) · 2.04 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(function(){
var utils = {
ajax: function(url,callback){
var XHR = (function(){
try{
if(window.XMLHttpRequest){
return new window.XMLHttpRequest();
}else{
return new window.ActiveXObject("Microsoft.XMLHTTP");
}
}catch(e){}
})();
var url = url;
XHR.open("get", url, true);
XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
XHR.onreadystatechange = function(){
if(XHR.readyState == 4 && XHR.status == 200){
// var ret = eval("(" + XHR.responseText + ")");
// var ret = new Function("return " + XHR.responseText )();
// extension中不能使用eval,new Function等方法
callback( unescape( XHR.responseText.replace(/\\/ig, '%') ) );
}
}
XHR.send(null);
},
// 简易模板
htmlEscape: function(s) {
if(s == null) return '';
s = s + '';
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'");
},
getPathData: function (data , path){
var type = $.type(data),
path = path + '',
dirs = path.split('.'),
dir;
/* 非数组或者非对象的data不处理 */
if(!(type=='array') && !(type=='object')){return 'error data';}
if(path == 'undefined'){return 'error path';}
while(dir = dirs.shift()){
if(data[dir]){
data = data[dir];
}else{
return null;
}
}
return data;
},
tmpl: function (tplStr, data) {
/**
* 一般模板替换时data为一个对象或者数组,这样在模板中可以通过制定path来获取相应值,从而个性化渲染模板,但也有可能传入data为string,如历史记录中的情况,这时把它包装成数组,便于在history模板中定制输出
*/
if($.type(data) == 'string'){data = [data]}
return tplStr.replace(/{([^}]*?)}/g, function ($0, $1) {
return data[$1] == null ? '' : utils.htmlEscape(utils.getPathData(data,$1));
});
}
};
window.utils = utils;
})();