Tuesday, February 14, 2017

Sample JavaScript to retrieve using Web API in Dynamics CRM 2016 / 365

function executeWebApiQuery(query, type) {
    var result = null;
    var clientURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest()
    req.open(type, encodeURI(clientURL + query), false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                result = JSON.parse(this.response);

            }
            else {
                var error = JSON.parse(this.response).error;
                alert("Error : " + error.message);
            }
        }
    };
    req.send(null);
    return result;
}


var query = "/api/data/v8.1/businessunits(" + BUID + ")?$select=name";
var type = "GET";
var queryResult = executeWebApiQuery(query, type);
if (queryResult.Value.length > 0) {
    var BUName = queryResult.Value[0].name;
}

No comments:

Post a Comment