博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Dynamics CRM 2011 JScript

Posted on 2015-10-31 18:42  Hamilton Tan  阅读(214)  评论(0编辑  收藏  举报
if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } }());
new_json.js
/*==================================================================

modifiedOn 12/9/2013 11:25AM
--------------------------------------------------------------------

fwREST v0.4.5

fwREST是用于CRM2011中使用REST访问OData服务进行数据操作的帮助js函数集。
使用时请用如下方式进行实例化:

var  r = new fwREST();

如果返回结果对象的.error != undefined 刚表明有错误,请使用 .error.message.value获取错误内容。

===================================================================*/
function fwREST(url) {
    var self = this;
    self.ServerUrl = null;
    if (url) {
        self.ServerUrl = url;
    } else {
        if (window.Xrm) {
            self.ServerUrl = Xrm.Page.context.getClientUrl();
        }
    }
    self.Async = false;
}
/*=================================================================
-------------------------------------------------------------------
方法:fwREST.create(entityname,jsondata)
说明:发送json形式的请求,用于创建记录。

entityname      字符串:实体名,需要使用逻辑名,区分大小写。如Account,New_test等
jsondata        字符串:JSON形式的请求内容,如"{'Name':'张三'}"
返回:object类型

==================================================================*/
fwREST.prototype.create = function (entityname, jsondata, callback) {
    var requestURL = this.ServerUrl + "/XRMServices/2011/OrganizationData.svc/" + entityname + "Set";
    //var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    var xmlhttp = new XMLHttpRequest();;
    xmlhttp.open("POST", requestURL, this.Async);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.setRequestHeader("Content-Length", jsondata.length);
    xmlhttp.setRequestHeader("Accept", "application/json");
    xmlhttp.send(jsondata);
    var jsonObject = eval("[" + xmlhttp.responseText + "]");
    //var jsonObject = JSON.parse(xmlhttp.responseText);
    if (jsonObject[0].error == undefined) {
        return jsonObject[0].d;
    } else {
        return jsonObject[0];
    }
}
/*=================================================================
-------------------------------------------------------------------
方法:fwREST.delete(entityname,objectid)
说明:发送json形式的请求,用于创建记录。

entityname      字符串:实体名,需要使用逻辑名,区分大小写。如Account,New_test等
objectid        记录ID。
返回:无

==================================================================*/
fwREST.prototype.del = function (entityname, objectid, callback) {
    var requestURL = this.ServerUrl_ + "/XRMServices/2011/OrganizationData.svc/" + entityname + "Set(guid'" + objectid + "')";
    var xmlhttp = new XMLHttpRequest();;
    xmlhttp.open("POST", requestURL, this.Async);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.setRequestHeader("Content-Length", 0);
    xmlhttp.setRequestHeader("Accept", "application/json");
    xmlhttp.setRequestHeader("x-http-method", "DELETE");
    xmlhttp.setRequestHeader("Accept-Encoding", "gzip, deflate");
    xmlhttp.onreadystatechange = function () { fwrest_delete_callback(xmlhttp, entityname, objectid, callback); };
    xmlhttp.send();
}
function fwrest_delete_callback(req, entityname, objectid, callback) {
    if (req.readyState == 4 /* complete */) {
        if (req.status == 204 || req.status == 1223) {
            if (callback != null) {
                callback(true);
            }
        }
        else {
            var jsonObject = eval("[" + req.responseText + "]");
            if (jsonObject[0].error == undefined) {
                if (callback != null) {
                    callback(true, entityname, objectid);
                }
            } else {
                if (callback != null) {
                    callback(jsonObject[0], entityname, objectid);
                }
            }
        }
    }
}


/*=================================================================
-------------------------------------------------------------------
方法:fwREST.update(entityname,id,jsondata)
说明:发送json形式的请求,用于更新记录。
参数:
entityname      字符串:实体名,需要使用逻辑名,区分大小写。如Account,New_test等
id              GUID,记录 ID
jsondata        字符串:JSON形式的请求内容,如"{'Name':'张三'}"
返回:无

==================================================================*/
fwREST.prototype.update = function (entityname, id, jsondata, callback, args) {
    var requestURL = this.ServerUrl + "/XRMServices/2011/OrganizationData.svc/" + entityname +
             "Set(guid'" + id + "')";
    var xmlhttp = new XMLHttpRequest();;
    xmlhttp.open("POST", requestURL, this.Async);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.setRequestHeader("Content-Length", jsondata.length);
    xmlhttp.setRequestHeader("x-http-method", "MERGE");
    xmlhttp.setRequestHeader("Accept", "application/json");
    xmlhttp.setRequestHeader("Accept-Encoding", "gzip, deflate");
    xmlhttp.eventArgs = args;
    _restCurrentRestObject = this;
    xmlhttp.onreadystatechange = function () { fwrest_update_callback(xmlhttp, callback, xmlhttp.eventArgs); };
    xmlhttp.send(jsondata);
}

function fwrest_update_callback(req, callback, args) {
    if (req.readyState == 4 /* complete */) {
        if (req.status == 204 || req.status == 1223) {
            if (callback != null) {
                callback(true, args);
            }
        }
        else {
            var jsonObject = eval("[" + req.responseText + "]");
            if (jsonObject[0].error == undefined) {
                if (callback != null) {
                    callback(true, args);
                }
            } else {
                if (callback != null) {
                    callback(jsonObject[0], args);
                }
            }
        }
    }
}

/*================================================================
------------------------------------------------------------------
方法:fwREST.get(parameter)
说明:能过REST参数做查询并返回结果。
参数:
parameter       字符串。参数内容,如"AccountSet?$select=Name"
返回:object类型

=================================================================*/

fwREST.prototype.get = function (parameter, callback) {
    var requestURL = this.ServerUrl + "/XRMServices/2011/OrganizationData.svc/" + parameter;
    var xmlhttp = new XMLHttpRequest();;
    xmlhttp.open("GET", requestURL, this.Async);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.setRequestHeader("Content-Length", 0);
    xmlhttp.setRequestHeader("Accept", "application/json");
    xmlhttp.send(null);
    var jsonObject = eval("[" + xmlhttp.responseText + "]");
    if (jsonObject[0].error != undefined) {
        return jsonObject[0];
    } else {
        if (jsonObject[0].d.results != undefined) {
            return jsonObject[0].d.results;
        } else {
            return jsonObject[0].d;
        }
    }
}
fw_rest.js