Saturday, December 8, 2012

SharePoint 2013 - Create a search app

It is not hard to create an App for search to use search javascript.

The search REST service is at http://site/_api/search/query?querytext='querytext'

In the app, need to add search permission,
 
In the default app page, the following html elements are defined.
<div id="toolbarDiv">
 
<input type="text" id="queryTerms" />
<button onclick="executeQuery($get('queryTerms').value); return false;">Search</button>
</div>
 
 
And here is the example script to send the query text to search service and display the results.

function executeQuery(queryTerms) {
    Results = {
        element: '',
        url: '',
        init: function (element) {
            Results.element = element;
            Results.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryTerms + "'";
        },
        load: function () {
            $.ajax({
                url: Results.url,
                method: "GET",
                headers: { "ACCEPT": "application/json" },
                success: Results.onSuccess,
                error: Results.onError
            });
        },
        onError: function (error) { alert(JSON.stringify(error)); },
        onSuccess: function (data) {
            var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
            var html = "<table>";
            for (var i = 0; i < results.length; i++) {
                html += "<tr><td>";
                html += results[i].Cells.results[3].Value;
                html += "</td><td>";
                html += results[i].Cells.results[6].Value;
                html += "</td></tr>";
                }
            html += "</table>";
            Results.element.html(html);
        }
    }
    Results.init($('#resultsDiv'));
    Results.load();
       
}

No comments: