SharePoint 2010 Rest API 错误(未检索数据)

SharePoint 2010 Rest API error (Not retrieving data)

当我 运行 下面的代码时,出现以下错误: "Unable to get property 'results' of undefined or null reference"

$(document).ready(function() { 
var iceCreamApp = {};
iceCreamApp.Truck = new Array();

//Load data from list into array right away
(function() {
    var url = "http://isaac.issharepoint.com/demo/_api/web/lists/GetByTitle('IceCreamTrucks')/items?$select=State";
    $.ajax({
        url:url,
        type:"GET",
        dataType:"json",
        headers: {"Accept": "application/json; odata=verbose"},
        success: function(data) {
            success(data);
        },
        error: function(data) {
            //failure(data);
        }
    })

        function success(data)
        {
            console.log(data);
        }
}());


})

您没有使用 REST。

如果您想使用 REST,您需要以下 URI:http://my.sharepoint.com/demo/_api/

您的代码示例可以使用 REST API 重写,如下所示:

(function() {
    var url = "http://my.sharepoint.com/demo/_api/web/lists/GetByTitle('IceCreamTrucks')/items?$select=State";
    $.ajax({
        url:url,
        type:"GET",
        dataType:"json",
        headers: {"Accept": "application/json; odata=verbose"},
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log(data);
        }
    })
}());

发生此错误是因为在 success 回调中您已经获得 results 对象:

success(data.d)  //<-- data.d returns results object

因此,解决方案是替换行

function success(data)
{
    console.log(data.d.results);
}

这个:

function success(results)
{
     console.log(results);
}

您也可以考虑使用 some library when working with SharePoint 2010 RESTful API. The following example demonstrates how get list items using datajs JavaScript library:

OData.read({ 
    requestUri: _spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/IceCreamTrucks?$select=State", 
    enableJsonpCallback: true
   }, 
   function (data) {
       for(var i =0; i < data.results.length; i++) {
           console.log(data.results[i].State);  
       } 
   }, 
   function (err) {
      // error function.
});