3

我有这个 Sharepoint (2010) Javascript(改编自此处)在 ListItem 中插入或更新各种“字段”:

var listId;

. . .

function upsertPostTravelListItemTravelerInfo1() {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

  var itemCreateInfo = new SP.ListItemCreationInformation();
  this.oListItem = oList.addItem(itemCreateInfo);

  listId = this.oListItem.ID;
  oListItem.set_item('ptli_formFilledOut', new Date());
  oListItem.set_item('ptli_TravelersName', $('travelername').val());
    . . .

  oListItem.update();

  clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

在上面的代码中,第一个“upsert”存储了“listId”;随后写入列表(将逐个写入,以防用户停止或某些东西停止了他们,他们稍后会返回)使用 getItemById() 方法获取先前开始的 ListItem:

function upsertPostTravelListItemTravelerInfo2() {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');
  this.oListItem = oList.getItemById(listId);

  oListItem.set_item('ptli_tripNumber', $('tripnumber').val());
    . . .

我的挑战是在用户想要在上面显示的两种方法中的第一种(upsertPostTravelListItemTravelerInfo1())中更新数据的第一位(他们插入这些数据,然后稍后返回并决定更改某些内容)的情况下。

我也需要在这里使用 getItemById() 。当这是第一个条目时,它还不存在,我使用:

listId = this.oListItem.ID;

...但是当这部分被更新时,将需要 listId 以便我可以:

this.oListItem = oList.getItemById(listId);

为此 - 为 listId 分配正确的值 - 我需要查询列表以查看某些值的“记录”是否已经存在,因此已经存在 listId;伪代码:

listId = //a "record" with a username value of "<userName>" and a payeeName of "<payeeName>" with a "Completed" value of "false")
if (listId == null) {
      var itemCreateInfo = new SP.ListItemCreationInformation();
      this.oListItem = oList.addItem(itemCreateInfo);
      listId = this.oListItem.ID;

} else {
      this.oListItem = oList.getItemById(listId);
}

我的问题是:我需要用什么替换该伪代码?如何像查询一样询问 Sharepoint 2010 ListItem 以找到特定 ListItem 成员值的匹配“记录”?

更新

基于 crclayton 的第一个想法,我在想:

function upsertPostTravelListItemTravelerInfo1() {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

  this.website = context.get_web();
  this.currentUser = website.get_currentUser();

  var itemCreateInfo = new SP.ListItemCreationInformation();
  this.oListItem = oList.addItem(itemCreateInfo);

  var travelersEmail = $('traveleremail').val());

  /* If this is an update, the call to getListItemID() will return a val; otherwise (an insert), get from newly instantiated ListItem.  */
  listId = getListItemID(currentUser, travelersEmail);
  if (listId === '') {
    listId = this.oListItem.ID; 
  }

  oListItem.set_item('ptli_formFilledOut', new Date());
  oListItem.set_item('ptli_TravelersName', $('travelername').val());
  oListItem.set_item('ptli_TravelersEmail', travelersEmail);
  . . .
}

function getListItemID(username, payeename) {
  var arrayListEnum = oList.getEnumerator();

  while (arrayListEnum.moveNext()) {
     var listItem = arrayListEnum.get_current();

     if(listItem.get_item("ptli_formPreparedBy") === username &&
        listItem.get_item("ptli_TravelersEmail") === payeename &&
        listItem.get_item("ptli_formCompleted") == false) {

         return listItem.get_id();    
     }
   }
   return '';
}

...可能是票。

更新 2

从答案中,我在这条线上得到了一个错误的消息:

var arrayListEnum = oList.getEnumerator();

即,“Uncaught TypeError: oList.getEnumerator is not a function”

是没有这样的名为getEnumerator()的函数,还是……???

更新 3

我仍然得到,“Uncaught TypeError: oList.getEnumerator is not a function”这个(修改过的)代码:

function getListItemID(username, payeename, oList) {
    var clientContext = new SP.ClientContext.get_current();
    var listItems = oList.getItems("");
    clientContext.load(listItems);
    clientContext.executeQueryAsync(function () {

        var arrayListEnum = oList.getEnumerator();

        while (arrayListEnum.moveNext()) {
            var listItem = arrayListEnum.get_current();

            if (listItem.get_item("userName") === "<userName>" &&
        listItem.get_item("payeeName") === "<payeeName>" &&
        listItem.get_item("Completed") == false) {

                return listItem.get_id();
            }
        }
        return '';
    });
}

我这样称呼它:

function upsertPostTravelListItemTravelerInfo1() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');

    this.website = clientContext.get_web();
    currentUser = website.get_currentUser();

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);

    var travelersEmail = $('traveleremail').val();

    /* If this is an update, the call to getListItemID() will return a val; otherwise (an insert), get from newly instantiated ListItem.  */
    listId = getListItemID(currentUser, travelersEmail, oList);
    if (listId === '') {
        listId = this.oListItem.ID;
    }

那么 getEnumerator() 是不是一个有效的函数?如果是,我做错了什么?如果没有,我可以用什么代替它?

4

2 回答 2

3

它可能不像您想要的那样类似于查询,但是像这样的东西呢:

 var clientContext = new SP.ClientContext.get_current();
 var listItems = oList.getItems("");
 clientContext.load(listItems);
 clientContext.executeQueryAsync(function(){

     var arrayListEnum = listItems.getEnumerator();

     while (arrayListEnum.moveNext()) {
         var listItem = arrayListEnum.get_current();

         if(listItem.get_item("userName") === "<userName>" &&
            listItem.get_item("payeeName") === "<payeeName>" &&
            listItem.get_item("Completed") == false) {

                return listItem.get_id();    
         }
     }
 });

或者您可以像这样使用 CAML 查询:

 var query = new SP.CamlQuery();
 query.set_viewXml("<View><Query><Where><Contains><FieldRef Name='userName'/>" +
                    "<Value Type='Text'>userName</Value></Contains></Where></Query>" + 
                    "</View>");
 listItems = oList.getItems(query);

 clientContext.load(listItems);
 clientContext.executeQueryAsync(onQuerySucceeded, function(){Alert("not found");});

 ...

 function onQuerySucceeded() {
    var listEnumerator = listItems.getEnumerator();
    while (listEnumerator.moveNext()) {
        console.log(listEnumerator.get_current().get_id());
    }  
 }
于 2015-10-09T21:40:58.640 回答
1

根据使用 SharePoint 2010 的请求使用REST 的 CRUD 示例

RESTful 服务的美妙之处--> 一切都发生在HTTP上

因此,您可以使用 pure JavaScript via XMLHttpRequest

JQuery 通过 $.ajax

通过本示例演示,因为它已在 SharePoint 2010 Web 部件中可用MicrosoftAjax.js Sys.Net.WebRequest

// test rest on SharePoint 2010
testREST();

function testREST() {
  /*
  **  List name: Test List (collapse spaces)
  **  Find list item - Set query in url --> ListName?$filter=
  **  Or access by list item id --> ListName(id)
  */
  invokeRequest({
    // make GET request with url query
    // REST also allows expansion of lookup fields
    //  --  here, i check `ModifiedBy` for `[Me]`
    'url': "TestList?$filter=" +
           "TextColumn eq 'row 1' and " +
           "NumberColumn lt 3 and " +
           "ModifiedById eq " + _spPageContextInfo.userId,

    // GET request
    'verb': "GET",

    // not needed for GET requests
    'body': null,
    'match': null,
    'method': null,

    // on complete
    'success': function (jsonObj) {
      // check the results of our query, returned in array: jsonObj.d.results
      // fyi -- if id used -- ListName(id) -- no array, one object: jsonObj.d
      if (jsonObj.d.results.length === 0) {
        // nothing found, insert new item
        insertItem();
      } else {
        // check field for _first_ item returned -- NumberColumn
        if (jsonObj.d.results[0].NumberColumn < 2) {
          // update if less than 2
          updateItem(jsonObj.d.results[0]);
        } else {
          // delete if greater than or equal to 2
          deleteItem(jsonObj.d.results[0]);
        }
      }
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

function insertItem() {
  /*
  **  List name: Test List
  **  Insert list item
  */
  invokeRequest({
    // make POST request for insert
    'url': "TestList",
    'verb': "POST",

    // use MicrosoftAjax.js to serialize our new list item
    'body': Sys.Serialization.JavaScriptSerializer.serialize({
      // set a key: value according to the column names in the list
      Title: "TEST",
      TextColumn: "row 1",
      EmployeeId: _spPageContextInfo.userId,
      NumberColumn: 1,
      DateColumn: new Date()
    }),

    // new item -- match & method not needed
    'match': null,
    'method': null,

    // on complete
    'success': function (jsonObj) {
      // print new list item to console
      var s = '';
      for (var key in jsonObj.d) {
        if (jsonObj.d.hasOwnProperty(key)) {
          s += key + ' = ' + jsonObj.d[key] + '\n';
        }
      }
      console.log('new list item\n' + s);
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

function updateItem(listItem) {
  /*
  **  List name: Test List
  **  Update list item
  */
  invokeRequest({
    // make POST request for insert -- set ID on url
    'url': "TestList(" + listItem.Id + ")",
    'verb': "POST",

    // serialize our updates -- literal w/ field name keys
    'body': Sys.Serialization.JavaScriptSerializer.serialize({
      Title: listItem.TextColumn + " test",
      NumberColumn: Number(listItem.NumberColumn) + 1
    }),

    // send the -- etag match -- for our update
    'match': listItem.__metadata.etag,

    // MERGE allows updates to one or more fields
    'method': "MERGE",

    // on complete
    'success': function (jsonObj) {
      // print request body -- _updated fields_ -- to console
      var newFields = Sys.Serialization.JavaScriptSerializer.deserialize(jsonObj.body);
      var s = '';
      for (var key in newFields) {
        if (newFields.hasOwnProperty(key)) {
          s += key + ' = ' + newFields[key] + '\n';
        }
      }
      console.log('updated list item\n' + s);
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

function deleteItem(listItem) {
  /*
  **  List name: Test List
  **  Delete list item
  */
  invokeRequest({
    // make POST request for delete -- set ID on url
    'url': "TestList(" + listItem.Id + ")",
    'verb': "POST",

    // no body needed for delete
    'body': null,

    // send the match for delete method
    'match': listItem.__metadata.etag,
    'method': "DELETE",

    // on complete
    'success': function (jsonObj) {
      // print request url for delete request
      console.log('deleted list item request\n' + jsonObj.url);
    },
    'fail': function (errCode, errMessage) {
      console.log(errCode + ' = ' + errMessage);
    },
  });
}

// invoke web request using [MicrosoftAjax.js](https://msdn.microsoft.com/en-us/library/vstudio/bb397536(v=vs.100).aspx)
function invokeRequest(requestObj) {
  // new web request
  var webRequest = new Sys.Net.WebRequest();

  // set request headers
  webRequest.get_headers()['Cache-Control'] = 'no-cache';
  webRequest.get_headers()['Accept'] = 'application/json';
  webRequest.get_headers()['Content-Type'] = 'application/json';

  // set etag match
  if (requestObj.match !== null) {
    webRequest.get_headers()['If-Match'] = requestObj.match;
  }

  // set method
  if (requestObj.method !== null) {
    webRequest.get_headers()['X-HTTP-Method'] = requestObj.method;
  }

  // set request verb
  webRequest.set_httpVerb(requestObj.verb);

  // set request body
  if (requestObj.body !== null) {
    webRequest.set_body(requestObj.body);
  }

  // set request url
  webRequest.set_url(
    _spPageContextInfo.webServerRelativeUrl + '/_vti_bin/ListData.svc/' + requestObj.url
  );

  // set user context
  webRequest.set_userContext(requestObj);

  // set completed callback and invoke request
  webRequest.add_completed(serviceComplete);
  webRequest.invoke();
}

// process web request
function serviceComplete(executor, args) {
  // check response
  if (executor.get_responseAvailable()) {
    // check status
    switch (executor.get_statusCode()) {
      case 200:   // OK
      case 201:   // Created
        // raise success callback - pass list item
        executor.get_webRequest().get_userContext().success(
          executor.get_object()
        );
        break;

      case 202:   // Accepted
      case 203:   // Non auth info
      case 204:   // No content
      case 205:   // Reset
      case 206:   // Partial
      case 1223:  // No content (SP)
        // raise success callback - pass original request object
        executor.get_webRequest().get_userContext().success(
          executor.get_webRequest().get_userContext()
        );
        break;

      // Error
      default:
        // raise fail callback - pass status
        executor.get_webRequest().get_userContext().fail(
          executor.get_statusCode(),
          executor.get_statusText()
        );
    }
  } else {
    // check timeout
    if (executor.get_timedOut()) {
      executor.get_webRequest().get_userContext().fail(408,'Request Timeout');
    } else {
      // check abort
      if (executor.get_aborted()) {
        executor.get_webRequest().get_userContext().fail(800,'Request Aborted');
      } else {
        executor.get_webRequest().get_userContext().fail(801,'Unknown Error');
      }
    }
  }
}

更多关于SharePoint 2010中的命名约定
更多关于spPageContextInfo

于 2015-10-12T20:38:09.140 回答