[Sharepoint 2013] Use jQuery Call REST Service

[Sharepoint 2013] Use jQuery Call REST Service

續上篇,http://www.dotblogs.com.tw/yc421206/archive/2014/06/12/145512.aspx

準備工作

  1. REST Endpoint Address
    http://msdn.microsoft.com/en-us/library/office/dn531433%28v=office.15%29.aspx
  2. 從 nuget 上安裝 jQuery,在這裡我是用 webform 專案

 

開始動手敲 code

用 jQuery.ajax 將資料查出來

    $.ajax({
        url: "http://localhost/_api/web/lists",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose",
        },
        success: successHandler,
        error: errorHandler
    });
});

 

成功將資料輸出

    $("#results").empty();
    var odataResults = data.d.results;
    var ul = $("<ul>");
    for (var i = 0; i < odataResults.length; i++) {
        $("<li>").html(odataResults[i].Title).appendTo(ul);
    }
    ul.appendTo("#results");
}

function errorHandler(data, errorCode, errorMessage) {
    document.write("Could not complete cross-domain call: " + errorMessage);

}

按下F5的執行結果,如下圖:

image

 

完整程式碼如下:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="/Scripts/jquery-2.1.1.js"></script>
    <script type="text/javascript" src="/Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">

        $(function () {
            $.ajax({
                url: "http://localhost/_api/web/lists",
                method: "GET",
                headers: {
                    "Accept": "application/json; odata=verbose",
                },
                success: successHandler,
                error: errorHandler
            });
        });
       
        function successHandler(data) {
            $("#results").empty();
            var odataResults = data.d.results;
            var ul = $("<ul>");
            for (var i = 0; i < odataResults.length; i++) {
                $("<li>").html(odataResults[i].Title).appendTo(ul);
            }
            ul.appendTo("#results");
        }

        function errorHandler(data, errorCode, errorMessage) {
            document.write("Could not complete cross-domain call: " + errorMessage);

        }
    </script>

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="results">
        </div>
    </form>
</body>
</html>


本文出自:http://www.dotblogs.com.tw/yc421206/archive/2014/06/19/145627.aspx

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo