解决SHAREJPOINT 跨域问题

目前仅支持IE7/8不支持IE11和谷歌

对于跨域情况,目前找到如果jquery是get获取方式,可以配置web.config相关属性,具体powershell命令如下:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

$localFarm = Get-SPFarm

$webapp = Get-SPWebApplication "http://wtcsps98"

# Remove old web.config modifications of MyAuthenticationProvider
$oldMods = @();
$webapp.WebConfigModifications | ? { $_.Owner -eq "CrossSiteScripting" } | % { 
$oldMods = $oldMods + $_
}

$oldMods | % { 
$webapp.WebConfigModifications.Remove($_) 
}

# update the Web Application and apply all existing web.config modifications - this executes the "remove" actions from above
$webapp.Update()
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.ApplyWebConfigModifications()

#Wait until web.config modifications finished by timer job
while( (Get-SPTimerJob | ? { $_.Name -eq "job-webconfig-modification"}) -ne $null ) {
Write-Host "." -NoNewline
Start-Sleep 1
}

# New web.config modifications for MyAuthenticationProvider
$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Allow-Origin'][@value='http://wtcsps99']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
#0 = for the enum value "SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Allow-Origin' value='http://wtcsps99' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Request-Method'][@value='GET,POST,HEAD,OPTIONS']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Request-Method' value='GET,POST,HEAD,OPTIONS' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Request-Headers'][@value='Content-Type,Authorization']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Request-Headers' value='Content-Type,Authorization' />"
$webapp.WebConfigModifications.Add($myModification1)

$myModification1 = new-object Microsoft.SharePoint.Administration.SPWebConfigModification
$myModification1.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$myModification1.Name = "add[@name='Access-Control-Allow-Credentials'][@value='true']"
$myModification1.Sequence = 0
$myModification1.Owner = "CrossSiteScripting"
$myModification1.Type = 0
$myModification1.Value = "<add name='Access-Control-Allow-Credentials' value='true' />"
$webapp.WebConfigModifications.Add($myModification1)

$webapp.Update()
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.ApplyWebConfigModifications()

#Wait until web.config modifications finished by timer job
while( (Get-SPTimerJob | ? { $_.Name -eq "job-webconfig-modification"}) -ne $null ) {
Write-Host "." -NoNewline
Start-Sleep 1
}

  

另外也需要在javascript里面进行相关配置,具体如下:

var Module = window.Module || {};
Module.GetTasks = (function () {
    var pub = {},
            _userId,            //userID of current user
            _tasks = [],        //List of our tasks
            _options = {
                listName: "Tasks List",                  //Name of list we want
                container: "#TaskListContainer",
                pulicUrl: "http://wtcsps98/sites/bpmmgmt"//id of html element we're rendering our list of tasks in
            };
    pub.init = function () {
        var clientContext = new SP.ClientContext.get_current();
        _userId = clientContext.get_web().get_currentUser();
        clientContext.load(_userId);

        //clientContext.load(_userId);
        clientContext.executeQueryAsync(GetDocDetail, _onQueryFailed);

    };

    function ReturnTaskCount(results) {
        var _tasks = results.d.results;
        var count = 0;
        var year = '2016';
        $.each(_tasks, function (index, task) {
            console.log(task.Status);
            year = GetYearValue(task.Title);
            if (parseInt(year) > 2014 && task.Status == 'Not Started') {
                count++;
            }

        });
        return count;
    }
    function getCountFormDigest(webUrl, listName) {
        var count = 0;
        $.support.cors = true;
        $.ajax({
            url: webUrl + "/_api/contextinfo",
            method: "POST",
            headers: { "Accept": "application/json; odata=verbose" },
            async: false,
            xhrFields: { "withCredentials": true },
            crossDomain: true,
            success: function (data) {
                count = getCountBySpecifiedList(data, listName, webUrl);
            },
            error: function (error) {
                console.log("Error in getting List: " + error);
                //$(_options.container).html("Error retrieving your " + listName + ".");
            }
        });
        return count;
    }
    function GetYearValue(taskTitle) {
        var year = '2016';
        var sTitle = taskTitle;
        var aTitle = sTitle.split('-');
        var title = aTitle[2].replace(/^s*/, '');
        year = title.substring(3, 7);
        console.log(year);
        return year;
    }
    function getCountBySpecifiedList(data, listName, webUrl) {
        var url = '', caml = '';
        var count = 0;
        var viewXml = "<View><Query><Where><Or><Eq><FieldRef Name='AssignedTo' /><Value Type='Integer'><UserID/></Value></Eq><Membership Type='CurrentUserGroups'><FieldRef Name='AssignedTo' /> </Membership></Or></Where></Query></View>";
        //var viewXml = "<View><Query><Where><And><And><Or><Eq><FieldRefName='AssignedTo'/><ValueType='Integer'><UserID/></Value></Eq><MembershipType='CurrentUserGroups'><FieldRefName='AssignedTo'/></Membership></Or><Neq><FieldRefName='Status'/><ValueType='Choice'>Completed</Value></Neq></And><Gt><FieldRefName='Created'/><ValueType='DateTime'>2014-09-28T12:00:00Z</Value></Gt></And></Where></Query></View>"
        $.support.cors = true;
        $.ajax({
            url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/getitems",
            method: "POST",
            async: true,
            //xhrFields: { "withCredentials": true },
            crossDomain: true,
            beforeSend: function(request) {
               request.setRequestHeader('Access-Control-Allow-Origin', 'http://wtcsps99');
               request.withCredentials = true;
            },
            data: "{ 'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, "ViewXml": ""
                + viewXml + "" }}",
            headers: {
                "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue,
                "Accept": "application/json; odata=verbose",
                "content-type": "application/json; odata=verbose"
            },
            success: function (results) {
                count = ReturnTaskCount(results);
            },
            error: function (error) {
                console.log("Error in getting List: " + listName);
                //$(_options.container).html("Error retrieving your " + listName + ".");
            }
        });
        return count;
    }
    function GetDocDetail() {
        console.log(_userId.get_loginName());
        var loginName = _userId.get_loginName();
        if (loginName == 'i:0#.w|wtc\setup.moss') {
            $(_options.container).html('its over');
            //return;

        }
        var showHtml = '';
        showHtml = '<div class="navitems_mc">';
        showHtml += '<ul class="activeTit">';
        $.support.cors = true;
        $.ajax({
            url: _options.pulicUrl + "/_api/web/lists/GetByTitle('Application Information')/items",
            type: "GET",
            headers: { "Accept": "application/json;odata=verbose" },
            async: false,
            xhrFields: { withCredentials: true },
            crossDomain: true,
            beforeSend: Loading,
            success: function (data) {
                var appInfo = data.d.results;
                if (appInfo) {
                    var count = 0;
                    var taskUrl = '';
                    var countTask = 0;
                    $.each(appInfo, function (index, item) {
                        taskUrl = item.SiteUrl + '/Lists/Tasks/MyItems.aspx';
                        countTask = getCountFormDigest(item.SiteUrl, item.TaskListName);
                        if (countTask > 0) {
                            showHtml += '<li class="navitems_mc_ul">';
                            showHtml += '<div class="classifydivv2" ><h2>' + item.CName + '</h2>';
                            showHtml += '<a href="' + taskUrl + '"><em>' + countTask + '</em></a>';
                            showHtml += '</div>';
                            showHtml += '</li>';
                        }

                    });
                }
            },
            error: function (xhr) {
                console.log(xhr.status + ': ' + xhr.statusText);
            }
        });
        showHtml += '</ul></div>';
        $(_options.container).html(showHtml);
    }
    function Loading() {
        var showHtml = '<b>数据加载中,请稍后...</b>';
        $(_options.container).html(showHtml);
    }
    function _onQueryFailed(sender, args) {
        alert('Request failed. 
Error: ' + args.get_message() + '
StackTrace: ' + args.get_stackTrace());
    }

    return pub;

}());

  

原文地址:https://www.cnblogs.com/hqbird/p/5833184.html