更新实体记录,代码如下
代码类似创建,差别在于创建使用POST,更新使用PATCH;更新无返回结果,204即表示更新成功。
function updateUsingWebAPI() {
var req = new XMLHttpRequest();
req.open("PATCH", encodeURI(Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts(AD43098E-38AD-E711-80C8-CD6AC961FE61)"), 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.send(JSON.stringify({
name: "Update Sample account",//文本类型
new_twooptions: false,//bool类型
new_money1: 100000,//货币类型
new_optionset: 2000,//选项集
new_date: new Date(),//日期
"new_lookup@odata.bind": "/accounts(D5957650-59A5-E711-80C5-AFF8F414EE97)"//查找类型
}));
req.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 204) {
alert("更新成功");
}
else {
var error = JSON.parse(req.response).error;
alert(error.message);
}
}
};
}
更新主要分两种情况,记录存在及记录不存在,以下详细说明
(1)实体记录存在的情况下,更新结果前后如下图
更新前:
更新后:
(2)实体记录若不存在,更新会变成创建,创建一条新的记录,结果如下
查询后发现所创建的记录GUID和代码中的GUID对应,即根据GUID创建了一条数据
req.open("PATCH", encodeURI(Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts(AD43098E-38AD-E711-80C8-CD6AC961FE50)"), true);
(3)如果只进行更新不进行创建在HTTP Request Header 中增加以下内容
If-Match | 只有请求内容与实体相匹配才有效 | If-Match: “737060cd8c284d8af7ad3082f209582d |
http://tools.jb51.net/table/http_header
http://blog.youkuaiyun.com/theowl/article/details/47251197
增加完后更新不存在的记录返回结果如下:
status返回结果为404,error.message提示account ID 不存在