SharePoint Code Snippets

1. ASP.NET路径中的“~”表示虚拟路径的根目录

2. 字符串太长时可用反斜杠来进行换行;

 return "<div style='background-color: #e5e5e5; width: 100px;  display:inline-block;'> \
            <div style='width: " + percentComplete.replace(/\s+/g, '') + "; background-color: #0094ff;'> \
            &nbsp;</div></div>&nbsp;" + percentComplete;

3. 

4. SharePoint REST API 设置List 权限;

// Change placeholder values before you run this code.
    var siteUrl = 'https://gejiaqi.sharepoint.com';
    var listTitle = 'SAP Region Approvers';
    var groupName = 'Jacky_s Team Site Members';
    var targetRoleDefinitionName = 'Contribute';
    var groupId;
    var targetRoleDefinitionId;
    
    $(document).ready( function() {
        var getGroupId = getTargetGroupId();
        getGroupId.done(function(){
            var getRoleDefId=getTargetRoleDefinitionId();
            getRoleDefId.done(function(responseData){
                targetRoleDefinitionId = responseData.d.Id;
                var breakRoleDefInh = breakRoleInheritanceOfList();
                breakRoleDefInh.done(function(){
                    var deleteRoles = deleteCurrentRoleForGroup();
                    deleteRoles.done(function(){
                        var setnewPermission = setNewPermissionsForGroup();
                        setnewPermission.done(function(){
                            successHandler();
                        });
                        setnewPermission.fail(errorHandler);
                    });
                    deleteRoles.fail(errorHandler);
                });
                breakRoleDefInh.fail(errorHandler);
            });
            getRoleDefId.fail(errorHandler);
        });
        getGroupId.fail(errorHandler);
    });
    
    // Get the ID of the target group.
    function getTargetGroupId() {
        var deferred=$.Deferred();
        $.ajax({
            url: siteUrl + '/_api/web/sitegroups/getbyname(\'' + groupName + '\')/id',
            type: 'GET',
            headers: { 'accept':'application/json;odata=verbose' },
            success: function(responseData) {
                groupId = responseData.d.Id;
                deferred.resolve();
            },
            error: function(error){
                deferred.reject();
            }
       });
       
       return deferred.promise();
    }
    
    // Get the ID of the role definition that defines the permissions
    // you want to assign to the group.
    function getTargetRoleDefinitionId() {
        return $.ajax({
            url: siteUrl + '/_api/web/roledefinitions/getbyname(\''
                + targetRoleDefinitionName + '\')/id',
            type: 'GET',
            headers: { 'accept':'application/json;odata=verbose' }
               });
    }
    
    // Break role inheritance on the list.
    function breakRoleInheritanceOfList() {
        return $.ajax({
            url: siteUrl + '/_api/web/lists/getbytitle(\'' + listTitle
                + '\')/breakroleinheritance(false)',
            type: 'POST',
            headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() }
        });
    }
    
    // Remove the current role assignment for the group on the list.
    function deleteCurrentRoleForGroup() {
        return $.ajax({
            url: siteUrl + '/_api/web/lists/getbytitle(\'' + listTitle
                + '\')/roleassignments/getbyprincipalid(' + groupId + ')',
            type: 'POST',
            headers: { 
                'X-RequestDigest':$('#__REQUESTDIGEST').val(),
                'X-HTTP-Method':'DELETE'
            }
         });
    }
    
    // Add the new role assignment for the group on the list.
    function setNewPermissionsForGroup() {
        return $.ajax({
            url: siteUrl + '/_api/web/lists/getbytitle(\'' + listTitle
                + '\')/roleassignments/addroleassignment(principalid='
                + groupId + ',roledefid=' + targetRoleDefinitionId + ')',
            type: 'POST',
            headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() }
        });
    }
    
    function successHandler() {
        alert('Request succeeded.');
    } 
    
    function errorHandler(xhr, ajaxOptions, thrownError) {
        alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
    }
View Code

5. Calendar Solution (SharePoint 2010版):隐藏Recurrence,会议室冲突检测,限制最早提前3个月预定;
Edit Form:

<script type="text/javascript">
      $(document).ready(function(){
          //hide 'Approval Status' field
          $('input[title="Approval Status"]').closest("tr").hide();
          hideField("Recurrence");
      });
      
      function hideField(title)
    {
        $(".ms-formtable").find("h3 nobr").each(function () {                
            var text = $(this).text();
            if(text==title)
            {
                   $(this).parent().parent().parent().hide();
            }
        })    
    }
      
      //-----------------------------------------Check Meeting Room Conflict, add limitation of 3 months-------------------------------------
          var startDateTime="";
        var endDateTime="";
        var meetingRoom ="";
        
        //overwrite PreSaveItem function, it is an empty function defined by default
        function PreSaveItem(){
            var startDate=$("input[title='Start Time']").val();
            var startHour=$("input[title='Start Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
            var startMinutes=$("input[title='Start Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();
            var endDate=$("input[title='End Time']").val();
            var endHour=$("input[title='End Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
            var endMinutes=$("input[title='End Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();

            var isAllDayEvent = $("input[id$='AllDayEventField']").attr("checked");
            if(isAllDayEvent == "checked"){
                startDateTime = startDate.replace(/\//g,"-")+"T00:00:00Z";
                endDateTime = endDate.replace(/\//g,"-")+"T23:59:00Z";
                
                startHour="00:";
                startMinutes="00";
                endHour="23:";
                endMinutes="59";
            }
            else{
                startDateTime = startDate.replace(/\//g,"-")+"T"+startHour+startMinutes+":00Z";
                endDateTime = endDate.replace(/\//g,"-")+"T"+endHour+endMinutes+":00Z";
            }
            
            meetingRoom = $("select[title='Meeting Room']").find("option:selected").text();
            
            //Check whether the seleted date is 3 months later
            var is3MonthsLater=false;
            var currentDate=new Date();
            var dateLimitation = addMonths(currentDate, 3);
            var selectedStartDate=new Date(startDate+ " "+ startHour+startMinutes);
            var selectedEndDate=new Date(endDate+ " " +endHour+endMinutes);
            
            if(dateLimitation.getTime()>selectedEndDate.getTime()){
                isMeetingRoomAvailable();
            }
            else{
                alert("You can book a meeting room at most 3 months in advance.\nPlease change the time slot.");
            }

            return false; //pause for the moment, because onQuerySucceeded is asynchronous
        }
        
        //Search for existing booking items based on parameters: meeting room, start time, end time;
        function isMeetingRoomAvailable(){
            var clientContext = SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('SEC会议室预定');
                
            var camlQuery = new SP.CamlQuery();
            var queryXML= "<View><Query>" +
                            "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                  "<FieldRef Name='EventDate' />" +
                                  "<FieldRef Name='EndDate' />" +
                                  "<FieldRef Name='Meeting_x0020_Room' />" +
                                  "<FieldRef Name='ID'/>" +
                           "</ViewFields>" +
                           "<Where>" +
                               "<And>" +
                              "<And>" +
                                  "<Or>" +
                                      "<Or>" +
                                        "<Or>" +
                                            "<And>" +
                                                "<Leq>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>" + startDateTime +"</Value>" +
                                                "</Leq>" +
                                                "<Gt>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                                "</Gt>" +
                                            "</And>" +
                                            "<And>" +
                                                "<Lt>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Lt>" +
                                                "<Geq>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Geq>" +
                                            "</And>" +
                                        "</Or>" +
                                        "<And>" +
                                            "<Geq>" +
                                               "<FieldRef Name='EventDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                            "</Geq>" +
                                            "<Leq>" +
                                               "<FieldRef Name='EndDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                            "</Leq>" +
                                        "</And>" +
                                    "</Or>" +
                                    "<And>" +
                                        "<Leq>" +
                                           "<FieldRef Name='EventDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                        "</Leq>" +
                                        "<Geq>" +
                                           "<FieldRef Name='EndDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                        "</Geq>" +
                                    "</And>" +
                                 "</Or>" +
                                 "<Eq>" +
                                    "<FieldRef Name='Meeting_x0020_Room' />" +
                                    "<Value Type='Lookup'>"+ meetingRoom +"</Value>" +
                                 "</Eq>" +
                              "</And>" +
                              "<Neq><FieldRef Name='Approval_x0020_Status'/><Value Type='Text'>Rejected</Value></Neq>" +
                            "</And>" +
                           "</Where>" +
                           "</Query></View>";
            camlQuery.set_viewXml(queryXML);
            this.collListItem = oList.getItems(camlQuery);
                
            clientContext.load(collListItem);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
        
        function onQuerySucceeded(sender, args){
            var itemsCount=this.collListItem.get_count();
            if(itemsCount == 0){    
                WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_ec1a1489_52a0_47c5_b701_fffcbb95806e$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true));
            }
            else{
                if(itemsCount == 1){
                    var queryStrs=getQueryStrings();
                    
                    if(queryStrs["ID"]==this.collListItem.get_item(0).get_id()){
                        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_ec1a1489_52a0_47c5_b701_fffcbb95806e$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true));
                    }
                    else{
                        alert("The selected meeting room is already booked for this time slot.\nPlease change meeting room or time slot.");
                    }
                }
                else{
                    alert("The selected meeting room is already booked for this time slot.\nPlease change meeting room or time slot.");
                }
            }
        }
        
        function onQueryFailed(sender, args){
            alert('Request failed. ' + args.get_message() + '\nPlease contact IT for help.');
        }
        
        function getQueryStrings(){
            var vars = [], hash;
            var q = document.URL.split('?')[1];
            if(q != undefined){
                q = q.split('&');
                for(var i = 0; i < q.length; i++){
                    hash = q[i].split('=');
                    vars.push(hash[1]);
                    vars[hash[0]] = hash[1];
                }
            }
            return vars;
        }
        
        //Add months to a date
        function addMonths(dateObj, num){
            var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
            dateObj.setMonth(dateObj.getMonth() + num);
            var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;
        
            // If don't get the right number, set date to 
            // last day of previous month
            if (diff != num) {
                dateObj.setDate(0);
            } 
            return dateObj;
        }

  </script>
View Code

New Form:

<script src="/sites/fcn/Customer_Solution/SiteAssets/jquery-1.11.0.min.js" type="text/javascript"></script><script type="text/javascript">


        $(document).ready(function(){
            //Hide the 'Approval Status' field
            $('input[title="Approval Status"]').closest("tr").hide();
            hideField("Recurrence");
        });
        
        function hideField(title)
        {
            $(".ms-formtable").find("h3 nobr").each(function () {                
                var text = $(this).text();
                if(text==title)
                {
                       $(this).parent().parent().parent().hide();
                }
            })    
        }
        
        
        //----------------------------------------Check Conflicts, Add limitation of 3 months-----------------------------------------------------------
        
        var startDateTime="";
        var endDateTime="";
        var meetingRoom ="";
        
        function PreSaveItem(){
            var startDate=$("input[title='Start Time']").val();
            var startHour=$("input[title='Start Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
            var startMinutes=$("input[title='Start Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();
            var endDate=$("input[title='End Time']").val();
            var endHour=$("input[title='End Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
            var endMinutes=$("input[title='End Time']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();

            var isAllDayEvent = $("input[id$='AllDayEventField']").attr("checked");
            if(isAllDayEvent == "checked"){
                startDateTime = startDate.replace(/\//g,"-")+"T00:00:00Z";
                endDateTime = endDate.replace(/\//g,"-")+"T23:59:00Z";
                
                startHour="00:";
                startMinutes="00";
                endHour="23:";
                endMinutes="59";
            }
            else{
                startDateTime = startDate.replace(/\//g,"-")+"T"+startHour+startMinutes+":00Z";
                endDateTime = endDate.replace(/\//g,"-")+"T"+endHour+endMinutes+":00Z";
            }
            
            meetingRoom = $("select[title='Meeting Room']").find("option:selected").text();
            
            //Check whether the seleted date is 3 months later
            var is3MonthsLater=false;
            var currentDate=new Date();
            var dateLimitation = addMonths(currentDate, 3);
            var selectedStartDate=new Date(startDate+ " "+ startHour+startMinutes);
            var selectedEndDate=new Date(endDate+ " " +endHour+endMinutes);
            
            if(dateLimitation.getTime()>selectedEndDate.getTime() && dateLimitation.getTime()>selectedEndDate.getTime()){
                isMeetingRoomAvailable();
            }
            else{
                alert("You can book a meeting room at most 3 months in advance.\nPlease change the time slot.");
            }

            return false; //pause for the moment
        }
        
        function isMeetingRoomAvailable(){
            var clientContext = SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('SEC会议室预定');
                
            var camlQuery = new SP.CamlQuery();
            var queryXML= "<View><Query>" +
                            "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                  "<FieldRef Name='EventDate' />" +
                                  "<FieldRef Name='EndDate' />" +
                                  "<FieldRef Name='Meeting_x0020_Room' />" +
                                  "<FieldRef Name='ID'/>" +
                           "</ViewFields>" +
                           "<Where>" +
                               "<And>" +
                              "<And>" +
                                  "<Or>" +
                                      "<Or>" +
                                        "<Or>" +
                                            "<And>" +
                                                "<Leq>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>" + startDateTime +"</Value>" +
                                                "</Leq>" +
                                                "<Gt>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                                "</Gt>" +
                                            "</And>" +
                                            "<And>" +
                                                "<Lt>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Lt>" +
                                                "<Geq>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Geq>" +
                                            "</And>" +
                                        "</Or>" +
                                        "<And>" +
                                            "<Geq>" +
                                               "<FieldRef Name='EventDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                            "</Geq>" +
                                            "<Leq>" +
                                               "<FieldRef Name='EndDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                            "</Leq>" +
                                        "</And>" +
                                    "</Or>" +
                                    "<And>" +
                                        "<Leq>" +
                                           "<FieldRef Name='EventDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                        "</Leq>" +
                                        "<Geq>" +
                                           "<FieldRef Name='EndDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                        "</Geq>" +
                                    "</And>" +
                                 "</Or>" +
                                 "<Eq>" +
                                    "<FieldRef Name='Meeting_x0020_Room' />" +
                                    "<Value Type='Lookup'>"+ meetingRoom +"</Value>" +
                                 "</Eq>" +
                              "</And>" +
                              "<Neq><FieldRef Name='Approval_x0020_Status'/><Value Type='Text'>Rejected</Value></Neq>" +
                            "</And>" +
                           "</Where>" +
                           "</Query></View>";
            camlQuery.set_viewXml(queryXML);
            this.collListItem = oList.getItems(camlQuery);
                
            clientContext.load(collListItem);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
        
        function onQuerySucceeded(sender, args){
            var itemsCount=this.collListItem.get_count();
            if(itemsCount == 0){    
                WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_8c59d4da_ca55_4bf8_a563_1cdcb25c7e06$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true));
            }
            else{
                alert("The selected meeting room is already booked for this time slot.\nPlease change meeting room or time slot.");
            }
        }
        
        function onQueryFailed(sender, args){
            alert('Request failed. ' + args.get_message() + '\nPlease contact IT for help.');
        }
        
        //Add months to a date
        function addMonths(dateObj, num){
            var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
            dateObj.setMonth(dateObj.getMonth() + num);
            var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;
        
            // If don't get the right number, set date to 
            // last day of previous month
            if (diff != num) {
                dateObj.setDate(0);
            } 
            return dateObj;
        }

    </script>
View Code

6. Calendar Solution (SharePoint 2013版):隐藏Recurrence,会议室冲突检测,限制最早提前3个月预定;

New Form:

<script src="jquery-1.11.1.min.js" type="text/javascript"></script>
      <script type="text/javascript">
          $(document).ready(function(){
            hideField("Recurrence");
        });
        
        function hideField(title)
        {
            $(".ms-formtable").find("h3 nobr").each(function () {                
                var text = $(this).text();
                if(text==title)
                {
                    $(this).parent().parent().parent().hide();
                }
            }) 
        }    
        
        //----------------------------------------Check Conflicts, Add limitation of 3 months-----------------------------------------------------------
        
        var startDateTime="";
        var endDateTime="";
        var meetingRoom ="";
        
        function PreSaveItem(){
            var isAllDayEvent = $("input[id$='AllDayEventField']").attr("checked");
            
            var startDate=$("input[title='Start Time Required Field']").val();
            var endDate=$("input[title='End Time Required Field']").val();

            //Check whether the seleted date is 3 months later
            var is3MonthsLater=false;
            var currentDate=new Date();
            var dateLimitation = addMonths(currentDate, 3);
            
            //get Date obj of selected start date and end date
            var selectedStartDateObj=new Date(startDate);
            var selectedEndDateObj=new Date(endDate);
            
            //get utc date string from Date object
            var utcStartDate= getUTCDate(selectedStartDateObj);
            var utcEndDate= getUTCDate(selectedEndDateObj);
            
            if(isAllDayEvent == "checked"){
                startDateTime = utcStartDate.replace(/\//g,"-")+"T00:00:00Z";
                endDateTime = utcEndDate.replace(/\//g,"-")+"T23:59:00Z";
                
                startHour="00:";
                startMinutes="00";
                endHour="23:";
                endMinutes="59";
            }
            else{
                var startHour=$("input[title='Start Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
                var startMinutes=$("input[title='Start Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();
                
                var endHour=$("input[title='End Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
                var endMinutes=$("input[title='End Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();
            
                startDateTime = utcStartDate.replace(/\//g,"-")+"T"+startHour+startMinutes+":00Z";
                endDateTime = utcEndDate.replace(/\//g,"-")+"T"+endHour+endMinutes+":00Z";
            }
            meetingRoom = $("select[title='Meeting Room Required Field']").find("option:selected").text();
            
            if(dateLimitation.getTime()>selectedStartDateObj.getTime() && dateLimitation.getTime()>selectedEndDateObj.getTime()){
                isMeetingRoomAvailable();
            }
            else{
                alert("You can book a meeting room at most 3 months in advance.\nPlease change the time slot.");
            }

            return false; //pause for the moment
        }
        
        //pass date object and return string in format of 'YYYY-M-D'
        function getUTCDate(date){
            var year=date.getFullYear();
            var month=date.getMonth()+1;
            var day=date.getDate();
            return year+"-"+month+"-"+day;
        }
        
        function isMeetingRoomAvailable(){
            var clientContext = SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('Meeting Room Reservation');
                
            var camlQuery = new SP.CamlQuery();
            var queryXML= "<View><Query>" +
                            "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                  "<FieldRef Name='EventDate' />" +
                                  "<FieldRef Name='EndDate' />" +
                                  "<FieldRef Name='Meeting_x0020_Room' />" +
                                  "<FieldRef Name='ID'/>" +
                           "</ViewFields>" +
                           "<Where>" +
                              "<And>" +
                                  "<Or>" +
                                      "<Or>" +
                                        "<Or>" +
                                            "<And>" +
                                                "<Leq>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>" + startDateTime +"</Value>" +
                                                "</Leq>" +
                                                "<Gt>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                                "</Gt>" +
                                            "</And>" +
                                            "<And>" +
                                                "<Lt>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Lt>" +
                                                "<Geq>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Geq>" +
                                            "</And>" +
                                        "</Or>" +
                                        "<And>" +
                                            "<Geq>" +
                                               "<FieldRef Name='EventDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                            "</Geq>" +
                                            "<Leq>" +
                                               "<FieldRef Name='EndDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                            "</Leq>" +
                                        "</And>" +
                                    "</Or>" +
                                    "<And>" +
                                        "<Leq>" +
                                           "<FieldRef Name='EventDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                        "</Leq>" +
                                        "<Geq>" +
                                           "<FieldRef Name='EndDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                        "</Geq>" +
                                    "</And>" +
                                 "</Or>" +
                                 "<Eq>" +
                                    "<FieldRef Name='Meeting_x0020_Room' />" +
                                    "<Value Type='Lookup'>"+ meetingRoom +"</Value>" +
                                 "</Eq>" +
                              "</And>" +
                           "</Where>" +
                           "</Query></View>";
            camlQuery.set_viewXml(queryXML);
            this.collListItem = oList.getItems(camlQuery);
                
            clientContext.load(collListItem);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
        
        function onQuerySucceeded(sender, args){
            var itemsCount=this.collListItem.get_count();
            if(itemsCount == 0){    
                WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl40$g_0ac0a4d5_5678_461f_bc36_1d8b7263adae$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true));
            }
            else{
                alert("The selected meeting room is already booked for this time slot.\nPlease change meeting room or time slot.");
            }
        }
        
        function onQueryFailed(sender, args){
            alert('Request failed. ' + args.get_message() + '\nPlease contact IT for help.');
        }
        
        //Add months to a date
        function addMonths(dateObj, num){
            var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
            dateObj.setMonth(dateObj.getMonth() + num);
            var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;
        
            // If don't get the right number, set date to 
            // last day of previous month
            if (diff != num) {
                dateObj.setDate(0);
            } 
            return dateObj;
        }

    </script>
View Code

Edit Form:

<script src="jquery-1.11.1.min.js" type="text/javascript"></script>
      <script type="text/javascript">    
          
        $(document).ready(function(){
            hideField("Recurrence");
        });
        
        function hideField(title)
        {
            $(".ms-formtable").find("h3 nobr").each(function () {                
                var text = $(this).text();
                if(text==title)
                {
                    $(this).parent().parent().parent().hide();
                }
            }) 
        }
    
        //----------------------------------------Check Conflicts, Add limitation of 3 months-----------------------------------------------------------
        
        var startDateTime="";
        var endDateTime="";
        var meetingRoom ="";
        
        function PreSaveItem(){
            var isAllDayEvent = $("input[id$='AllDayEventField']").attr("checked");
            
            var startDate=$("input[title='Start Time Required Field']").val();
            var endDate=$("input[title='End Time Required Field']").val();

            //Check whether the seleted date is 3 months later
            var is3MonthsLater=false;
            var currentDate=new Date();
            var dateLimitation = addMonths(currentDate, 3);
            
            //get Date obj of selected start date and end date
            var selectedStartDateObj=new Date(startDate);
            var selectedEndDateObj=new Date(endDate);
            
            //get utc date string from Date object
            var utcStartDate= getUTCDate(selectedStartDateObj);
            var utcEndDate= getUTCDate(selectedEndDateObj);
            
            if(isAllDayEvent == "checked"){
                startDateTime = utcStartDate.replace(/\//g,"-")+"T00:00:00Z";
                endDateTime = utcEndDate.replace(/\//g,"-")+"T23:59:00Z";
                
                startHour="00:";
                startMinutes="00";
                endHour="23:";
                endMinutes="59";
            }
            else{
                var startHour=$("input[title='Start Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
                var startMinutes=$("input[title='Start Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();
                
                var endHour=$("input[title='End Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateHours']").val();
                var endMinutes=$("input[title='End Time Required Field']").closest("tr").find("select[id$='DateTimeField_DateTimeFieldDateMinutes']").val();
            
                startDateTime = utcStartDate.replace(/\//g,"-")+"T"+startHour+startMinutes+":00Z";
                endDateTime = utcEndDate.replace(/\//g,"-")+"T"+endHour+endMinutes+":00Z";
            }
            meetingRoom = $("select[title='Meeting Room Required Field']").find("option:selected").text();
            
            if(dateLimitation.getTime()>selectedStartDateObj.getTime() && dateLimitation.getTime()>selectedEndDateObj.getTime()){
                isMeetingRoomAvailable();
            }
            else{
                alert("You can book a meeting room at most 3 months in advance.\nPlease change the time slot.");
            }

            return false; //pause for the moment, because onQuerySucceeded is asynchronous
        }
        
        function getUTCDate(date){
            var year=date.getFullYear();
            var month=date.getMonth()+1;
            var day=date.getDate();
            return year+"-"+month+"-"+day;
        }
        
        function isMeetingRoomAvailable(){
            var clientContext = SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('Meeting Room Reservation');
                
            var camlQuery = new SP.CamlQuery();
            var queryXML= "<View><Query>" +
                            "<ViewFields>" +
                                "<FieldRef Name='Title' />" +
                                  "<FieldRef Name='EventDate' />" +
                                  "<FieldRef Name='EndDate' />" +
                                  "<FieldRef Name='Meeting_x0020_Room' />" +
                                  "<FieldRef Name='ID'/>" +
                           "</ViewFields>" +
                           "<Where>" +
                              "<And>" +
                                  "<Or>" +
                                      "<Or>" +
                                        "<Or>" +
                                            "<And>" +
                                                "<Leq>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>" + startDateTime +"</Value>" +
                                                "</Leq>" +
                                                "<Gt>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                                "</Gt>" +
                                            "</And>" +
                                            "<And>" +
                                                "<Lt>" +
                                                    "<FieldRef Name='EventDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Lt>" +
                                                "<Geq>" +
                                                    "<FieldRef Name='EndDate' />" +
                                                    "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                                "</Geq>" +
                                            "</And>" +
                                        "</Or>" +
                                        "<And>" +
                                            "<Geq>" +
                                               "<FieldRef Name='EventDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                            "</Geq>" +
                                            "<Leq>" +
                                               "<FieldRef Name='EndDate' />" +
                                               "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                            "</Leq>" +
                                        "</And>" +
                                    "</Or>" +
                                    "<And>" +
                                        "<Leq>" +
                                           "<FieldRef Name='EventDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ startDateTime +"</Value>" +
                                        "</Leq>" +
                                        "<Geq>" +
                                           "<FieldRef Name='EndDate' />" +
                                           "<Value Type='DateTime' IncludeTimeValue='TRUE'>"+ endDateTime +"</Value>" +
                                        "</Geq>" +
                                    "</And>" +
                                 "</Or>" +
                                 "<Eq>" +
                                    "<FieldRef Name='Meeting_x0020_Room' />" +
                                    "<Value Type='Lookup'>"+ meetingRoom +"</Value>" +
                                 "</Eq>" +
                              "</And>" +
                           "</Where>" +
                           "</Query></View>";
            camlQuery.set_viewXml(queryXML);
            this.collListItem = oList.getItems(camlQuery);
                
            clientContext.load(collListItem);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
        
        function onQuerySucceeded(sender, args){
            var itemsCount=this.collListItem.get_count();
            if(itemsCount == 0){    
                WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl40$g_e34ff01e_9d1c_4a02_9b7e_5ea0dc169f43$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true));
            }
            else{
                if(itemsCount == 1){
                    var queryStrs=getQueryStrings();
                    
                    if(queryStrs["ID"]==this.collListItem.get_item(0).get_id()){
                        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl40$g_e34ff01e_9d1c_4a02_9b7e_5ea0dc169f43$ctl00$toolBarTbl$RightRptControls$ctl00$ctl00$diidIOSaveItem", "", true, "", "", false, true));
                    }
                    else{
                        alert("The selected meeting room is already booked for this time slot.\nPlease change meeting room or time slot.");
                    }
                }
                else{
                    alert("The selected meeting room is already booked for this time slot.\nPlease change meeting room or time slot.");
                }
            }
        }
        
        function onQueryFailed(sender, args){
            alert('Request failed. ' + args.get_message() + '\nPlease contact IT for help.');
        }
        
        //Add months to a date
        function addMonths(dateObj, num){
            var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
            dateObj.setMonth(dateObj.getMonth() + num);
            var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;
        
            // If don't get the right number, set date to 
            // last day of previous month
            if (diff != num) {
                dateObj.setDate(0);
            } 
            return dateObj;
        }
        
        function getQueryStrings(){
            var vars = [], hash;
            var q = document.URL.split('?')[1];
            if(q != undefined){
                q = q.split('&');
                for(var i = 0; i < q.length; i++){
                    hash = q[i].split('=');
                    vars.push(hash[1]);
                    vars[hash[0]] = hash[1];
                }
            }
            return vars;
        }

    </script>
View Code

7. jQuery遍历页面上的item链接<a>标签并使其在 SPModalDialog 中打开,

//User Defined Function to Open Dialog Framework
                function openDialog(strPageURL) 
                {
                  var dialogOptions = SP.UI.$create_DialogOptions();
                  dialogOptions.url = strPageURL;// URL of the Page
                  //dialogOptions.width = 750; // Width of the Dialog
                  //dialogOptions.height = 500; // Height of the Dialog
                  
                  SP.UI.ModalDialog.showModalDialog(dialogOptions); // Open the Dialog
                  return false; //don't refresh page
                }
                
                $(document).ready(function(){
                    $("#toolsDiv a").each(function(){
                        if($(this).attr("href").toLowerCase().indexOf("/_layouts/listform.aspx?")>=0){
                            $(this).click(function(){
                                return openDialog($(this).attr("href"));
                            });
                        }
                    });
                });

7. Survey中实现Radio button 与 Textbox关联的示例:选中yes后,textbox必填,否则Next按钮不能点击

/*----------------------Make textbox mandatory when select yes in Q2-------------------------------*/
              function checkComment()
            {
                var isEmpty=true;
                $("textarea").each(function(){
                    if($.trim($(this).text()).length!=0){
                        isEmpty=false;
                    }
                });
                return isEmpty;
            }
            
            function checkQ2RadioButtons()
            {
                var isYesSelected = false;
                var titleAttr = $(":radio[name='ctl00$m$g_f84c1a24_be7c_4140_a098_ff1e7b13cec1$ctl00$ctl02$ctl01$ctl00$ctl00$ctl04$ctl00$RadioButtons']:checked").parent().attr("title");
                if(titleAttr == "Yes" )
                {
                    isYesSelected = true;
                }
                return isYesSelected;
            }
            
            $(function(){
                //make comments required when select yes in Q2
                  $("td[class='ms-formlabel']:contains('If yes, please specify.')").css("border-top", "0px"); //hide the line between two questions
                  
                  //add change event for Q2 radio buttons
                $(":radio[name='ctl00$m$g_f84c1a24_be7c_4140_a098_ff1e7b13cec1$ctl00$ctl02$ctl01$ctl00$ctl00$ctl04$ctl00$RadioButtons']").on("change", function(){
                          var isCommentEmpty = checkComment();
                          
                          var responseValue = $(this).parent().attr("title");
                          
                          if (responseValue == "Yes")
                          {
                              if(isCommentEmpty)
                              {
                                  $("input[id$='ctl00_diidIONextPage']").each(function(){
                                      $(this).attr("disabled", "disabled");
                                  });
                              }
                          }
                          else
                          {
                                $("input[id$='ctl00_diidIONextPage']").each(function(){
                                  $(this).removeAttr("disabled");
                              });
                          }
                });    
                
                $("textarea").change(function(){
                    var isEmpty=checkComment();
                    if(isEmpty && checkQ2RadioButtons()){
                        $("input[id$='ctl00_diidIONextPage']").each(function(){
                            $(this).attr("disabled", "disabled");
                        });
                    }
                    else
                    {
                        $("input[id$='ctl00_diidIONextPage']").each(function(){
                            $(this).removeAttr("disabled");
                        });
                    }
                });
            });
View Code

8. 简单地将表单以modal dialog形式展示:

<a style='border: 0' href="#" onclick='SP.UI.ModalDialog.ShowPopupDialog("http://XXX/_layouts/FormServer.aspx?XsnLocation=http://XXX/XXXLibrary/Forms/template.xsn&SaveLocation=XXX&ClientInstalled=false&Source=XXX&DefaultItemOpen=1"); return false;'><img src='XXX/SiteAssets/FontAwesome.png' alt='' title='' /></a>

即把打开后的表单地址直接拷贝粘贴到ShowPopupDialog()方法的参数中;

9. 简单地以Modal Dialog形式展现一个弹出窗口的方法:

//User Defined Function to Open Dialog Framework
function openDialog(strPageURL) 
{
    var dialogOptions = SP.UI.$create_DialogOptions();
    dialogOptions.url = strPageURL;// URL of the Page                  
    SP.UI.ModalDialog.showModalDialog(dialogOptions); // Open the Dialog
     return false;
}

10. 在SharePoint 2013中,可以在 Provider-Host的 Add-in中使用 cross-domain library来读取host web或者 add-in web中的内容:

(1) Get the host web title using the cross-domain library (JSOM)

var hostweburl;
var appweburl;

// Load the required SharePoint libraries
$(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl")
    );

    // resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";

    // Load the js files and continue to the successHandler
    $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js",
                function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
                );
        }
        );
});

// Function to prepare and issue the request to get
//  SharePoint data
function execCrossDomainRequest() {
    // context: The ClientContext object provides access to
    //      the web and lists objects.
    // factory: Initialize the factory object with the
    //      app web URL.
    var context;
    var factory;
    var hostSite;

    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    hostSite = new SP.AppContextSite(context, hostweburl);

    this.web = hostSite.get_web();
    context.load(this.web);

    //Execute the query with all the previous 
    //  options and parameters
    context.executeQueryAsync(
        Function.createDelegate(this, successHandler), 
        Function.createDelegate(this, errorHandler)
    );

    // Function to handle the success event.
    // Prints the host web's title to the page.
    function successHandler() {
        document.getElementById("HostwebTitle").innerHTML =
            "<b>" + this.web.get_title() + "</b>";
    }

    // Function to handle the error event.
    // Prints the error message to the page.
    function errorHandler(data, errorCode, errorMessage) {
        document.getElementById("HostwebTitle").innerText =
            "Could not complete cross-domain call: " + errorMessage;
    }
}

// Function to retrieve a query string value.
// For production purposes you may want to use
//  a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
View Code

(2) Get the host web title using the cross-domain library (REST)

var hostweburl;
var appweburl;

// Load the required SharePoint libraries
$(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl")
    );

    // resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";

    // Load the js file and continue to the 
    //   success event handler
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});

// Function to prepare and issue the request to get
//  SharePoint data
function execCrossDomainRequest() {
    var executor;

    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);

    // Issue the call against the host web.
    // To get the title using REST we can hit the endpoint:
    //      app_web_url/_api/SP.AppContextSite(@target)/web/title?@target='siteUrl'
    // The response formats the data in the JSON format.
    // The functions successHandler and errorHandler attend the
    //      success and error events respectively.
    executor.executeAsync(
        {
            url:
                appweburl +
                "/_api/SP.AppContextSite(@target)/web/title?@target='" +
                hostweburl + "'",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: successHandler,
            error: errorHandler
        }
    );
}

// Function to handle the success event.
// Prints the host web's title to the page.
function successHandler(data) {
    var jsonObject = JSON.parse(data.body);

    document.getElementById("HostwebTitle").innerHTML =
        "<b>" + jsonObject.d.Title + "</b>";
}

// Function to handle the error event.
// Prints the error message to the page.
function errorHandler(data, errorCode, errorMessage) {
    document.getElementById("HostwebTitle").innerText =
        "Could not complete cross-domain call: " + errorMessage;
}

// Function to retrieve a query string value.
// For production purposes you may want to use
//  a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
View Code

(3) Get list items from add-in web by using the cross-domain library (REST)

var hostweburl;
var appweburl;

// Load the required SharePoint libraries
$(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl")
    );

    // resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";

    // Load the js files and continue to the successHandler
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});

// Function to prepare and issue the request to get
//  SharePoint data
function execCrossDomainRequest() {
    // executor: The RequestExecutor object
    // Initialize the RequestExecutor with the app web URL.
    var executor = new SP.RequestExecutor(appweburl);

    // Issue the call against the app web.
    // To get the title using REST we can hit the endpoint:
    //      appweburl/_api/web/lists/getbytitle('listname')/items
    // The response formats the data in the JSON format.
    // The functions successHandler and errorHandler attend the
    //      sucess and error events respectively.
    executor.executeAsync(
        {
            url:
                appweburl +
                "/_api/web/lists/getbytitle('Announcements')/items",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: successHandler,
            error: errorHandler
        }
    );
}

// Function to handle the success event.
// Prints the data to the page.
function successHandler(data) {
    var jsonObject = JSON.parse(data.body);
    var announcementsHTML = "";

    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++) {
        announcementsHTML = announcementsHTML +
            "<p><h1>" + results[i].Title +
            "</h1>" + results[i].Body +
            "</p><hr>";
    }

    document.getElementById("renderAnnouncements").innerHTML =
        announcementsHTML;
}

// Function to handle the error event.
// Prints the error message to the page.
function errorHandler(data, errorCode, errorMessage) {
    document.getElementById("renderAnnouncements").innerText =
        "Could not complete cross-domain call: " + errorMessage;
}

// Function to retrieve a query string value.
// For production purposes you may want to use
//  a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
View Code

(4) Get list items from add-in web by using the cross-domain library (JSOM)

// The allAnnouncements variable is used by more than one 
//  function to retrieve and process the results.
var allAnnouncements;
var hostweburl;
var appweburl;

// Load the required SharePoint libraries
$(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl")
    );

    // resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";

    // Load the js files and continue to the successHandler
    $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js",
                function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
                );
        }
        );
});

// Function to prepare and issue the request to get
//  SharePoint data
function execCrossDomainRequest() {
    // context: The ClientContext object provides access to
    //      the web and lists objects.
    // factory: Initialize the factory object with the
    //      app web URL.
    var context = new SP.ClientContext(appweburl);
    var factory =
        new SP.ProxyWebRequestExecutorFactory(
            appweburl
        );
    context.set_webRequestExecutorFactory(factory);

    //Get the web and list objects
    //  and prepare the query
    var web = context.get_web();
    var list = web.get_lists().getByTitle("Announcements");
    var camlString =
        "<View><ViewFields>" +
            "<FieldRef Name='Title' />" +
            "<FieldRef Name='Body' />" +
        "</ViewFields></View>";

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlString);
    allAnnouncements = list.getItems(camlQuery);

    context.load(allAnnouncements, "Include(Title, Body)");

    //Execute the query with all the previous 
    //  options and parameters
    context.executeQueryAsync(
        successHandler, errorHandler
    );
}

// Function to handle the success event.
// Prints the data to the page.
function successHandler(data, req) {
    var announcementsHTML = "";
    var enumerator = allAnnouncements.getEnumerator();

    while (enumerator.moveNext()) {
        var announcement = enumerator.get_current();
        announcementsHTML = announcementsHTML +
            "<p><h1>" + announcement.get_item("Title") +
            "</h1>" + announcement.get_item("Body") +
            "</p><hr>";
    }

    document.getElementById("renderAnnouncements").innerHTML =
        announcementsHTML;
}

// Function to handle the error event.
// Prints the error message to the page.
function errorHandler(data, error, errorMessage) {
    document.getElementById("renderAnnouncements").innerText =
        "Could not complete cross-domain call: " +
        errorMessage;
}

// Function to retrieve a query string value.
// For production purposes you may want to use
//  a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}
View Code

Note: 在使用REST方式读取Host Web 和 Add-in Web内容时,只有一点区别:executor.executeAsync()方法的 url 参数不同;

//读取Host Web中的内容:
url: appweburl + "/_api/SP.AppContextSite(@target)/web/title?@target='" + hostweburl + "'",

//读取Add-in Web中的内容
url: appweburl + "/_api/web/lists/getbytitle('Announcements')/items",

 在使用JSOM方式读取Host Web 和 Add-in Web内容时,也只有一点区别:是否需要获取 Host Web 对象;

//读取Host Web中的内容:
var appContext = new SP.ClientContext(appweburl);
var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
appContext.set_webRequestExecutorFactory(factory);
var hostSite = new SP.AppContextSite(appContext, hostweburl);
var web = hostSite.get_web();
//读取Add-in Web中的内容 var appContext = new SP.ClientContext(appweburl); var factory = new SP.ProxyWebRequestExecutorFactory(appweburl); appContext.set_webRequestExecutorFactory(factory);
var web = context.get_web();

11. jQuery调用 Custom REST Service 的例子(GET),参考此文章

<script src="/XXX/SiteAssets/jquery-1.11.1.min.js"></script> 

<h2>SharePoint 2013: Consume a custom WCF REST service hosted in SharePoint 2013.</h2>
<h3>This is a quick sample to demonstrate calling a custom SharePoint-hosted WCF REST service from a
    Script Editor Web Part using simple HTML, JavaScript and JQuery.
</h3>

<div>
    <br />
    <p id="message">Loading presidents...</p>
</div>

<div id="resultsPanel"></div>

<script type="text/javascript">
    $(document).ready(function () {
        getPresidentsData();
    });
  
function getPresidentsData() {
    var serviceUri = _spPageContextInfo.webAbsoluteUrl +
        "/_vti_bin/CustomRESTService.svc/getallpresidents";
    $.ajax({
        type: "GET",
        contentType: "application/json;charset=utf-8",
        url: serviceUri,
        dataType: "json",
        success:
            function (response) {
                $('#resultsPanel').html("");
                showPresidentsList(response.GetAllPresidentsResult);
                $('#message').html("<a href=" + serviceUri + ">" + serviceUri + "</a>");
            },
        error:
            function (err) {
                alert(err);
            }
    });
}

function showPresidentsList(presidentsData) {
    $.each($(presidentsData), function (index, item) {
        $('#resultsPanel').append(item.Id + ' - ');
        $('#resultsPanel').append(item.FirstName + ' ');
        $('#resultsPanel').append(item["LastName"] + ' (');
        $('#resultsPanel').append(item["EmailAddress"] + ')');
        $('#resultsPanel').append('<br><br>');
    });
}
</script>
View Code

返回的数据格式为:

效果为:

12. SharePoint 2010中,使用 Client OM 从列表中获取数据并显示在Status Bar中:

ExecuteOrDelayUntilScriptLoaded(displayNotification, "sp.js");
                
                var lastUpdatedItemsInfo = '';
                
                function displayNotification(){
                    getLastUpdatedItems();
                }

                function getLastUpdatedItems() {
                    var ctx = SP.ClientContext.get_current();
                    var web = ctx.get_web();
                    var oList= web.get_lists().getByTitle('Last Updated Items');
                    var camlQuery = new SP.CamlQuery();
                    camlQuery.set_viewXml('<View><RowLimit>10</RowLimit><Query><OrderBy><FieldRef Name="ID" Ascending="FALSE"/></OrderBy></Query></View>'); //如果需要查询数据,只需要在<Query></Query>标签中添加<Where></Where>标签就可以
                    var collListItem = oList.getItems(camlQuery);    
                    ctx.load(collListItem);
                    var mySuccessCallBack = Function.createCallback(onQueryLastUpdateItemsSucceeded, collListItem);                
                    ctx.executeQueryAsync(Function.createDelegate(this, mySuccessCallBack), Function.createDelegate(this, this.onQueryLastUpdatedItemsFailed));
                }
                
                function onQueryLastUpdateItemsSucceeded(sender, args, collListItem) {
                    var listItemEnumerator = collListItem.getEnumerator(); 
                    while (listItemEnumerator.moveNext()) {
                        var oListItem = listItemEnumerator.get_current();
                        lastUpdatedItemsInfo += ' <span class="customStatus" onClick="openDialog(\''+oListItem.get_item('Link')+'\')">'+oListItem.get_item('Title')+'</span>,';
                    }
                    lastUpdatedItemsInfo = lastUpdatedItemsInfo.toString();
                    if(lastUpdatedItemsInfo.length>0)
                    {
                        lastUpdatedItemsInfo =lastUpdatedItemsInfo.slice(0,-1);
                        var statusId = SP.UI.Status.addStatus("Last Updated:",lastUpdatedItemsInfo);
                        SP.UI.Status.setStatusPriColor(statusId, "cobalt");
                    }
                }
                
                function onQueryLastUpdatedItemsFailed(sender, args) {
                    lastUpdatedItemsInfo = '';
                }              

                function openDialog(strPageURL) 
                {
                  var dialogOptions = SP.UI.$create_DialogOptions();
                  dialogOptions.url = strPageURL;// URL of the Page
                  
                  SP.UI.ModalDialog.showModalDialog(dialogOptions); // Open the Dialog
                  return false;
                }

13. 

 

 

 

posted @ 2010-02-21 15:36  Jacky Ge  阅读(340)  评论(0编辑  收藏  举报