关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复209或者20160318可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!
执行乐观并发的更新或者删除,关键的修改是增加 If-Match 这个请求头。每次查询记录都会返回记录的版本号。示例代码如下:
var clientURL = Xrm.Page.context.getClientUrl(); var req = new XMLHttpRequest() req.open("GET", encodeURI(clientURL + "/api/data/v8.0/ly_tests(94B750DA-17B9-E511-80DC-000D3A804C3F)?$select=ly_name"), true); 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) { var responseJSON = JSON.parse(this.responseText); Xrm.Utility.alertDialog("查询到的记录的版本号是" + responseJSON["@odata.etag"] + " ,请修改记录后点击确定!"); req.open("PATCH", encodeURI(clientURL + "/api/data/v8.0/ly_tests(94B750DA-17B9-E511-80DC-000D3A804C3F)"), true); req.setRequestHeader("If-Match", responseJSON["@odata.etag"]); 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 /* complete */) { req.onreadystatechange = null; if (this.status == 204) { Xrm.Utility.alertDialog("记录修改成功!") } else { var error = JSON.parse(this.response).error; Xrm.Utility.alertDialog("修改罗勇测试实体记录出错." + error.message); } } }; var test = {}; test.ly_name = "单行文本";//单行文本 req.send(JSON.stringify(test)); } else { var error = JSON.parse(this.responseText).error; Xrm.Utility.alertDialog("查询罗勇测试实体记录出错." + error.message); } } }; req.send();
测试截图如下,证实有效。
更多信息请参考官方文档:Perform conditional operations using the Web API 。