다음을 통해 공유


샘플: JavaScript와 함께 OData 끝점을 사용하여 만들기, 검색, 업데이트 및 삭제

 

게시 날짜: 2016년 11월

적용 대상: Dynamics CRM 2015

이 샘플 코드는 Microsoft Dynamics CRM 2015 및 Microsoft Dynamics CRM Online 2015 업데이트용입니다.Microsoft Dynamics CRM SDK 패키지를 다운로드합니다. 다운로드 패키지의 다음 위치에서 확인할 수 있습니다.

SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations

이 샘플이 어떻게 작동되는지 확인하려면 다운로드 파일에 포함된 JavaScriptRESTDataOperations_1_0_0_1_managed.zip 관리형 솔루션을 설치할(가져올) 수 있습니다. 이 관리형 솔루션을 설치한 후 수행되는 작업을 확인하기 위해 솔루션 구성 페이지를 봅니다.

이 관리 솔루션을 설치하고 이 항목의 이름을 사용하여 웹 리소스를 만들려면 관리형 솔루션을 제거(삭제)하지 않는 한 솔루션 게시자 사용자 지정 접두사는 “sample”일 수 없습니다.

요구 사항

이 샘플에서는 다음과 같은 리소스를 사용합니다.

  • sample_/JavaScriptRESTDataOperationsSample.htm
    이 샘플에 대한 UI 요소가 포함된 HTML 페이지입니다.

  • sample_/Scripts/JavaScriptRESTDataOperationsSample
    페이지의 UI 요소를 관리하는 기능과 샘플에서 수행되는 작업이 포함된 라이브러리입니다.

  • sample_/Scripts/SDK.REST.js
    웹 리소스에 대해 REST 끝점을 사용하여 비동기 데이터 작업을 간소화하는 재사용 가능한 일반 라이브러리입니다.

참고

사용자 지정 접두사 "sample_"은 코드에 사용되지 않습니다. 이러한 샘플은 게시자의 사용자 지정 접두사를 사용하여 작동합니다. 하지만 시뮬레이션된 Scripts 폴더의 상대 경로는 웹 리소스 이름에 포함되어야 합니다.

보여 주기

이 샘플:

  • REST 끝점 및 JavaScript를 사용하여 가장 기본적인 데이터 작업을 수행하는 방법을 보여 줍니다.

  • Microsoft Dynamics CRM 2015 및 Microsoft Dynamics CRM Online 2015 업데이트에서 지원하는 웹 브라우저가 포함된 XMLHttpRequest 개체를 사용합니다.

  • 새 거래처 레코드에 대한 작업을 순차적으로 실행합니다. 이 샘플을 실행할 때 만든 레코드를 삭제할 수 있는 옵션이 있습니다.

  • sample_/JavaScriptRESTDataOperationsSample.htm 웹 리소스를 미리 보면 다음과 같은 결과가 표시 됩니다.

    Setting the primary contact to: <the full name of the first Contact record in your system>. 
    Setting Preferred Contact Method to E-mail. 
    Setting Annual Revenue to Two Million .
    Setting Contact Method Phone to "Do Not Allow".
    The account named "Test Account Name" was created with the AccountId : "7780cef2-fdf4-e011-9d26-00155dba3819".
    Retrieving account with the AccountId: "7780cef2-fdf4-e011-9d26-00155dba3819".
    Retrieved the account named "Test Account Name". This account was created on : "Wed Oct 12 11:13:56 PDT 2011".
    Changing the account Name to "Updated Account Name".
    Adding Address information
    Setting E-Mail address
    The account record changes were saved
    You chose to delete the account record.
    The account was deleted.
    

sample_/JavaScriptRESTDataOperationsSample.htm

이 페이지는 몇 가지 설명과 샘플을 시작하고 다시 설정하는 단추를 제공합니다.


<html lang="en-us">
<head>
 <title>JavaScript REST Data Operations</title>
 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- /WebResources/ClientGlobalContext.js.aspx is accessed using a relative path
because the name of the Web Resource created from this file is "sample_/JavaScriptRESTDataOperationsSample.htm".

The use of the backslash within the name creates a virtual folder that must be considered
in relative links between Web Resources.
-->
 <script src="../ClientGlobalContext.js.aspx"></script>
 <script src="Scripts/SDK.REST.js" type="text/javascript"></script>
 <script src="Scripts/JavaScriptRESTDataOperationsSample.js" type="text/javascript"></script>


</head>
<body style="background-color: White; font-family:Segoe UI;">
<h1>JavaScript REST Endpoint Data Operations Sample</h1>
<p>This page uses the <b>sample_/Scripts/JavaScriptRESTDataOperationsSample.js</b> JScript library to create, retrieve, and update an
 account record. It also provides the option to delete or view the record.</p>
<p>The <b>sample_/Scripts/JavaScriptRESTDataOperationsSample.js</b> JScript library uses the <b>sample_/Scripts/SDK.REST.js</b> JScript library to perform the data operations.</p>
<p>Use the buttons below to verify the functionality of this sample.</p>
 <button id="start" title="Click this button to start the sample.">
  Start</button>
 <button id="reset" title="Click this button to reset the sample." disabled="disabled">
  Reset</button>
 <ol id="output">
 </ol>
</body>
</html>

sample_/Scripts/JavaScriptRESTDataOperationsSample

이 라이브러리에는 페이지의 UI 요소를 관리하는 기능과 샘플에서 수행되는 작업이 포함됩니다. 이 라이브러리의 함수는 sample_/Scripts/SDK.REST.js에 있는 재사용 가능한 일반 메서드에 따라 다릅니다.


var primaryContact = null;
var startButton;
var resetButton;
var output; //The <ol> element used by the writeMessage function to display text showing the progress of this sample.

document.onreadystatechange = function () {
 if (document.readyState == "complete") {
  getFirstContactToBePrimaryContact();

  startButton = document.getElementById("start");
  resetButton = document.getElementById("reset");
  output = document.getElementById("output");

  startButton.onclick = createAccount;
  resetButton.onclick = resetSample;
 }
}

function createAccount() {
 var account = {};
 account.Name = "Test Account Name";
 account.Description = "This account was created by the JavaScriptRESTDataOperations sample.";
 if (primaryContact != null) {
  //Set a lookup value
  writeMessage("Setting the primary contact to: " + primaryContact.FullName + ".");
  account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: "contact", Name: primaryContact.FullName };

 }
 //Set a picklist value
 writeMessage("Setting Preferred Contact Method to E-mail.");
 account.PreferredContactMethodCode = { Value: 2 }; //E-mail

 //Set a money value
 writeMessage("Setting Annual Revenue to Two Million .");
 account.Revenue = { Value: "2000000.00" }; //Set Annual Revenue

 //Set a Boolean value
 writeMessage("Setting Contact Method Phone to \"Do Not Allow\".");
 account.DoNotPhone = true; //Do Not Allow

 //Add Two Tasks
 var today = new Date();
 var startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 3); //Set a date three days in the future.

 var LowPriTask = { Subject: "Low Priority Task", ScheduledStart: startDate, PriorityCode: { Value: 0} }; //Low Priority Task
 var HighPriTask = { Subject: "High Priority Task", ScheduledStart: startDate, PriorityCode: { Value: 2} }; //High Priority Task
 account.Account_Tasks = [LowPriTask, HighPriTask]



 //Create the Account
 SDK.REST.createRecord(
     account,
     "Account",
     function (account) {
      writeMessage("The account named \"" + account.Name + "\" was created with the AccountId : \"" + account.AccountId + "\".");
      writeMessage("Retrieving account with the AccountId: \"" + account.AccountId + "\".");
      retrieveAccount(account.AccountId)
     },
     errorHandler
   );
 this.setAttribute("disabled", "disabled");
}

function retrieveAccount(AccountId) {
 SDK.REST.retrieveRecord(
     AccountId,
     "Account",
     null,null,
     function (account) {
      writeMessage("Retrieved the account named \"" + account.Name + "\". This account was created on : \"" + account.CreatedOn + "\".");
      updateAccount(AccountId);
     },
     errorHandler
   );
}

function updateAccount(AccountId) {
 var account = {};
 writeMessage("Changing the account Name to \"Updated Account Name\".");
 account.Name = "Updated Account Name";
 writeMessage("Adding Address information");
 account.Address1_AddressTypeCode = { Value: 3 }; //Address 1: Address Type = Primary
 account.Address1_City = "Sammamish";
 account.Address1_Line1 = "123 Maple St.";
 account.Address1_PostalCode = "98074";
 account.Address1_StateOrProvince = "WA";
 writeMessage("Setting E-Mail address");
 account.EMailAddress1 = "someone@microsoft.com";


 SDK.REST.updateRecord(
     AccountId,
     account,
     "Account",
     function () {
      writeMessage("The account record changes were saved");
      deleteAccount(AccountId);
     },
     errorHandler
   );
}

function deleteAccount(AccountId) {
 if (confirm("Do you want to delete this account record?")) {
  writeMessage("You chose to delete the account record.");
  SDK.REST.deleteRecord(
       AccountId,
       "Account",
       function () {
        writeMessage("The account was deleted.");
        enableResetButton();
       },
       errorHandler
     );
 }
 else {
  var li = document.createElement("li");

  var span = document.createElement("span");

  setElementText(span, "You chose not to delete the record. You can view the record ");


  var link = document.createElement("a");
  link.href = SDK.REST._getClientUrl() + "/main.aspx?etc=1&amp;id=%7b" + AccountId + "%7d&amp;pagetype=entityrecord";
  link.target = "_blank";
  setElementText(link, "here");


  li.appendChild(span);
  li.appendChild(link);
  output.appendChild(li);
  enableResetButton();

 }
}

function getFirstContactToBePrimaryContact() {

 SDK.REST.retrieveMultipleRecords(
     "Contact",
     "$select=ContactId,FullName&amp;$top=1",
     function (results) {
      var firstResult = results[0];
      if (firstResult != null) {
       primaryContact = results[0];
      }
      else {
       writeMessage("No Contact records are available to set as the primary contact for the account.");
      }
     },
     errorHandler,
     function () { 
     //OnComplete handler
      }
   );
}

function errorHandler(error) {
 writeMessage(error.message);
}

function enableResetButton() {
 resetButton.removeAttribute("disabled");
}

function resetSample() {
 output.innerHTML = "";
 startButton.removeAttribute("disabled");
 resetButton.setAttribute("disabled", "disabled");
}

//Helper function to write data to this page:
function writeMessage(message) {
    var li = document.createElement("li");

    setElementText(li, message);


 output.appendChild(li);
}
//Because Firefox doesn't  support innerText
function setElementText(element, text)
{
    if (element.innerText != undefined)
    {
        element.innerText = text;
    }
    else
    {
        element.textContent = text;
    }
}

sample_/Scripts/SDK.REST.js

이 라이브러리에는 다음 작업에 대한 공용 메서드가 포함되어 있습니다.

  • SDK.REST.createRecord

  • SDK.REST.retrieveRecord

  • SDK.REST.updateRecord

  • SDK.REST.deleteRecord

  • SDK.REST.retrieveMultipleRecords

  • SDK.REST.associateRecords

  • SDK.REST.disassociateRecords

이러한 각 메서드에는 successCallbackerrorCallback 매개 변수가 포함됩니다. 이러한 매개 변수는 데이터 작업이 성공하거나 실패하는 경우 호출되는 함수에 대한 참조를 허용합니다.SDK.REST.associateRecordsSDK.REST.disassociateRecords 메서드를 사용하는 예제는 샘플: JavaScript와 함께 OData 끝점을 사용하여 레코드 연결 및 연결 해제를 참조하십시오.


if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
SDK.REST = {
 _context: function () {
  ///<summary>
  /// Private function to the context object.
  ///</summary>
  ///<returns>Context</returns>
  if (typeof GetGlobalContext != "undefined")
  { return GetGlobalContext(); }
  else {
   if (typeof Xrm != "undefined") {
    return Xrm.Page.context;
   }
   else
   { throw new Error("Context is not available."); }
  }
 },
 _getClientUrl: function () {
  ///<summary>
  /// Private function to return the server URL from the context
  ///</summary>
  ///<returns>String</returns>
  var clientUrl = this._context().getClientUrl()

  return clientUrl;
 },
 _ODataPath: function () {
  ///<summary>
  /// Private function to return the path to the REST endpoint.
  ///</summary>
  ///<returns>String</returns>
  return this._getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
 },
 _errorHandler: function (req) {
  ///<summary>
  /// Private function return an Error object to the errorCallback
  ///</summary>
  ///<param name="req" type="XMLHttpRequest">
  /// The XMLHttpRequest response that returned an error.
  ///</param>
  ///<returns>Error</returns>
  //Error descriptions come from https://support.microsoft.com/kb/193625
  if (req.status == 12029)
  { return new Error("The attempt to connect to the server failed."); }
  if (req.status == 12007)
  { return new Error("The server name could not be resolved."); }
  var errorText;
  try
        { errorText = JSON.parse(req.responseText).error.message.value; }
  catch (e)
        { errorText = req.responseText }

  return new Error("Error : " +
        req.status + ": " +
        req.statusText + ": " + errorText);
 },
 _dateReviver: function (key, value) {
  ///<summary>
  /// Private function to convert matching string values to Date objects.
  ///</summary>
  ///<param name="key" type="String">
  /// The key used to identify the object property
  ///</param>
  ///<param name="value" type="String">
  /// The string value representing a date
  ///</param>
  var a;
  if (typeof value === 'string') {
   a = /Date\(([-+]?\d+)\)/.exec(value);
   if (a) {
    return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
   }
  }
  return value;
 },
 _parameterCheck: function (parameter, message) {
  ///<summary>
  /// Private function used to check whether required parameters are null or undefined
  ///</summary>
  ///<param name="parameter" type="Object">
  /// The parameter to check;
  ///</param>
  ///<param name="message" type="String">
  /// The error message text to include when the error is thrown.
  ///</param>
  if ((typeof parameter === "undefined") || parameter === null) {
   throw new Error(message);
  }
 },
 _stringParameterCheck: function (parameter, message) {
  ///<summary>
  /// Private function used to check whether required parameters are null or undefined
  ///</summary>
  ///<param name="parameter" type="String">
  /// The string parameter to check;
  ///</param>
  ///<param name="message" type="String">
  /// The error message text to include when the error is thrown.
  ///</param>
  if (typeof parameter != "string") {
   throw new Error(message);
  }
 },
 _callbackParameterCheck: function (callbackParameter, message) {
  ///<summary>
  /// Private function used to check whether required callback parameters are functions
  ///</summary>
  ///<param name="callbackParameter" type="Function">
  /// The callback parameter to check;
  ///</param>
  ///<param name="message" type="String">
  /// The error message text to include when the error is thrown.
  ///</param>
  if (typeof callbackParameter != "function") {
   throw new Error(message);
  }
 },
 createRecord: function (object, type, successCallback, errorCallback) {
  ///<summary>
  /// Sends an asynchronous request to create a new record.
  ///</summary>
  ///<param name="object" type="Object">
  /// A JavaScript object with properties corresponding to the Schema name of
  /// entity attributes that are valid for create operations.
  ///</param>
  ///<param name="type" type="String">
  /// The Schema Name of the Entity type record to create.
  /// For an Account record, use "Account"
  ///</param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called by a successful response. 
  /// This function can accept the returned record as a parameter.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  this._parameterCheck(object, "SDK.REST.createRecord requires the object parameter.");
  this._stringParameterCheck(type, "SDK.REST.createRecord requires the type parameter is a string.");
  this._callbackParameterCheck(successCallback, "SDK.REST.createRecord requires the successCallback is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.createRecord requires the errorCallback is a function.");
  var req = new XMLHttpRequest();
  req.open("POST", encodeURI(this._ODataPath() + type + "Set"), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 201) {
     successCallback(JSON.parse(this.responseText, SDK.REST._dateReviver).d);
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  req.send(JSON.stringify(object));
 },
 retrieveRecord: function (id, type, select, expand, successCallback, errorCallback) {
  ///<summary>
  /// Sends an asynchronous request to retrieve a record.
  ///</summary>
  ///<param name="id" type="String">
  /// A String representing the GUID value for the record to retrieve.
  ///</param>
  ///<param name="type" type="String">
  /// The Schema Name of the Entity type record to retrieve.
  /// For an Account record, use "Account"
  ///</param>
  ///<param name="select" type="String">
  /// A String representing the $select OData System Query Option to control which
  /// attributes will be returned. This is a comma separated list of Attribute names that are valid for retrieve.
  /// If null all properties for the record will be returned
  ///</param>
  ///<param name="expand" type="String">
  /// A String representing the $expand OData System Query Option value to control which
  /// related records are also returned. This is a comma separated list of of up to 6 entity relationship names
  /// If null no expanded related records will be returned.
  ///</param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called by a successful response. 
  /// This function must accept the returned record as a parameter.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  this._stringParameterCheck(id, "SDK.REST.retrieveRecord requires the id parameter is a string.");
  this._stringParameterCheck(type, "SDK.REST.retrieveRecord requires the type parameter is a string.");
  if (select != null)
   this._stringParameterCheck(select, "SDK.REST.retrieveRecord requires the select parameter is a string.");
  if (expand != null)
   this._stringParameterCheck(expand, "SDK.REST.retrieveRecord requires the expand parameter is a string.");
  this._callbackParameterCheck(successCallback, "SDK.REST.retrieveRecord requires the successCallback parameter is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveRecord requires the errorCallback parameter is a function.");

  var systemQueryOptions = "";

  if (select != null || expand != null) {
   systemQueryOptions = "?";
   if (select != null) {
    var selectString = "$select=" + select;
    if (expand != null) {
     selectString = selectString + "," + expand;
    }
    systemQueryOptions = systemQueryOptions + selectString;
   }
   if (expand != null) {
    systemQueryOptions = systemQueryOptions + "&amp;$expand=" + expand;
   }
  }


  var req = new XMLHttpRequest();
  req.open("GET", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')" + systemQueryOptions), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 200) {
     successCallback(JSON.parse(this.responseText, SDK.REST._dateReviver).d);
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  req.send();
 },
 updateRecord: function (id, object, type, successCallback, errorCallback) {
  ///<summary>
  /// Sends an asynchronous request to update a record.
  ///</summary>
  ///<param name="id" type="String">
  /// A String representing the GUID value for the record to retrieve.
  ///</param>
  ///<param name="object" type="Object">
  /// A JavaScript object with properties corresponding to the Schema Names for
  /// entity attributes that are valid for update operations.
  ///</param>
  ///<param name="type" type="String">
  /// The Schema Name of the Entity type record to retrieve.
  /// For an Account record, use "Account"
  ///</param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called by a successful response. 
  /// Nothing will be returned to this function.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  this._stringParameterCheck(id, "SDK.REST.updateRecord requires the id parameter.");
  this._parameterCheck(object, "SDK.REST.updateRecord requires the object parameter.");
  this._stringParameterCheck(type, "SDK.REST.updateRecord requires the type parameter.");
  this._callbackParameterCheck(successCallback, "SDK.REST.updateRecord requires the successCallback is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.updateRecord requires the errorCallback is a function.");
  var req = new XMLHttpRequest();

  req.open("POST", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')"), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.setRequestHeader("X-HTTP-Method", "MERGE");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 204 || this.status == 1223) {
     successCallback();
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  req.send(JSON.stringify(object));
 },
 deleteRecord: function (id, type, successCallback, errorCallback) {
  ///<summary>
  /// Sends an asynchronous request to delete a record.
  ///</summary>
  ///<param name="id" type="String">
  /// A String representing the GUID value for the record to delete.
  ///</param>
  ///<param name="type" type="String">
  /// The Schema Name of the Entity type record to delete.
  /// For an Account record, use "Account"
  ///</param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called by a successful response. 
  /// Nothing will be returned to this function.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  this._stringParameterCheck(id, "SDK.REST.deleteRecord requires the id parameter.");
  this._stringParameterCheck(type, "SDK.REST.deleteRecord requires the type parameter.");
  this._callbackParameterCheck(successCallback, "SDK.REST.deleteRecord requires the successCallback is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.deleteRecord requires the errorCallback is a function.");
  var req = new XMLHttpRequest();
  req.open("POST", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')"), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.setRequestHeader("X-HTTP-Method", "DELETE");
  req.onreadystatechange = function () {

   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 204 || this.status == 1223) {
     successCallback();
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  req.send();

 },
 retrieveMultipleRecords: function (type, options, successCallback, errorCallback, OnComplete) {
  ///<summary>
  /// Sends an asynchronous request to retrieve records.
  ///</summary>
  ///<param name="type" type="String">
  /// The Schema Name of the Entity type record to retrieve.
  /// For an Account record, use "Account"
  ///</param>
  ///<param name="options" type="String">
  /// A String representing the OData System Query Options to control the data returned
  ///</param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called for each page of records returned.
  /// Each page is 50 records. If you expect that more than one page of records will be returned,
  /// this function should loop through the results and push the records into an array outside of the function.
  /// Use the OnComplete event handler to know when all the records have been processed.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  ///<param name="OnComplete" type="Function">
  /// The function that will be called when all the requested records have been returned.
  /// No parameters are passed to this function.
  /// </param>
  this._stringParameterCheck(type, "SDK.REST.retrieveMultipleRecords requires the type parameter is a string.");
  if (options != null)
   this._stringParameterCheck(options, "SDK.REST.retrieveMultipleRecords requires the options parameter is a string.");
  this._callbackParameterCheck(successCallback, "SDK.REST.retrieveMultipleRecords requires the successCallback parameter is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveMultipleRecords requires the errorCallback parameter is a function.");
  this._callbackParameterCheck(OnComplete, "SDK.REST.retrieveMultipleRecords requires the OnComplete parameter is a function.");

  var optionsString;
  if (options != null) {
   if (options.charAt(0) != "?") {
    optionsString = "?" + options;
   }
   else
   { optionsString = options; }
  }
  var req = new XMLHttpRequest();
  req.open("GET", this._ODataPath() + type + "Set" + optionsString, true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 200) {
     var returned = JSON.parse(this.responseText, SDK.REST._dateReviver).d;
     successCallback(returned.results);
     if (returned.__next != null) {
      var queryOptions = returned.__next.substring((SDK.REST._ODataPath() + type + "Set").length);
      SDK.REST.retrieveMultipleRecords(type, queryOptions, successCallback, errorCallback, OnComplete);
     }
     else
     { OnComplete(); }
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  req.send();
 },
 associateRecords: function (parentId, parentType, relationshipName, childId, childType, successCallback, errorCallback) {
  this._stringParameterCheck(parentId, "SDK.REST.associateRecords requires the parentId parameter is a string.");
  ///<param name="parentId" type="String">
  /// The Id of the record to be the parent record in the relationship
  /// </param>
  ///<param name="parentType" type="String">
  /// The Schema Name of the Entity type for the parent record.
  /// For an Account record, use "Account"
  /// </param>
  ///<param name="relationshipName" type="String">
  /// The Schema Name of the Entity Relationship to use to associate the records.
  /// To associate account records as a Parent account, use "Referencedaccount_parent_account"
  /// </param>
  ///<param name="childId" type="String">
  /// The Id of the record to be the child record in the relationship
  /// </param>
  ///<param name="childType" type="String">
  /// The Schema Name of the Entity type for the child record.
  /// For an Account record, use "Account"
  /// </param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called by a successful response. 
  /// Nothing will be returned to this function.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  this._stringParameterCheck(parentType, "SDK.REST.associateRecords requires the parentType parameter is a string.");
  this._stringParameterCheck(relationshipName, "SDK.REST.associateRecords requires the relationshipName parameter is a string.");
  this._stringParameterCheck(childId, "SDK.REST.associateRecords requires the childId parameter is a string.");
  this._stringParameterCheck(childType, "SDK.REST.associateRecords requires the childType parameter is a string.");
  this._callbackParameterCheck(successCallback, "SDK.REST.associateRecords requires the successCallback parameter is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.associateRecords requires the errorCallback parameter is a function.");

  var req = new XMLHttpRequest();
  req.open("POST", encodeURI(this._ODataPath() + parentType + "Set(guid'" + parentId + "')/$links/" + relationshipName), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 204 || this.status == 1223) {
     successCallback();
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  var childEntityReference = {}
  childEntityReference.uri = this._ODataPath() + "/" + childType + "Set(guid'" + childId + "')";
  req.send(JSON.stringify(childEntityReference));
 },
 disassociateRecords: function (parentId, parentType, relationshipName, childId, successCallback, errorCallback) {
  this._stringParameterCheck(parentId, "SDK.REST.disassociateRecords requires the parentId parameter is a string.");
  ///<param name="parentId" type="String">
  /// The Id of the record to be the parent record in the relationship
  /// </param>
  ///<param name="parentType" type="String">
  /// The Schema Name of the Entity type for the parent record.
  /// For an Account record, use "Account"
  /// </param>
  ///<param name="relationshipName" type="String">
  /// The Schema Name of the Entity Relationship to use to disassociate the records.
  /// To disassociate account records as a Parent account, use "Referencedaccount_parent_account"
  /// </param>
  ///<param name="childId" type="String">
  /// The Id of the record to be disassociated as the child record in the relationship
  /// </param>
  ///<param name="successCallback" type="Function">
  /// The function that will be passed through and be called by a successful response. 
  /// Nothing will be returned to this function.
  /// </param>
  ///<param name="errorCallback" type="Function">
  /// The function that will be passed through and be called by a failed response. 
  /// This function must accept an Error object as a parameter.
  /// </param>
  this._stringParameterCheck(parentType, "SDK.REST.disassociateRecords requires the parentType parameter is a string.");
  this._stringParameterCheck(relationshipName, "SDK.REST.disassociateRecords requires the relationshipName parameter is a string.");
  this._stringParameterCheck(childId, "SDK.REST.disassociateRecords requires the childId parameter is a string.");
  this._callbackParameterCheck(successCallback, "SDK.REST.disassociateRecords requires the successCallback parameter is a function.");
  this._callbackParameterCheck(errorCallback, "SDK.REST.disassociateRecords requires the errorCallback parameter is a function.");

  var req = new XMLHttpRequest();
  req.open("POST", encodeURI(this._ODataPath() + parentType + "Set(guid'" + parentId + "')/$links/" + relationshipName + "(guid'" + childId + "')"), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.setRequestHeader("X-HTTP-Method", "DELETE");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 204 || this.status == 1223) {
     successCallback();
    }
    else {
     errorCallback(SDK.REST._errorHandler(this));
    }
   }
  };
  req.send();
 },
 __namespace: true
};

참고 항목

웹 리소스와 함께 OData 끝점 사용
샘플: JavaScript 및 jQuery와 함께 OData 끝점을 사용하여 만들기, 검색, 업데이트 및 삭제
기술 문서: REST 끝점과 함께 옵션 집합 옵션 사용 - JScript

© 2017 Microsoft. All rights reserved. 저작권 정보