Skip to content

Instantly share code, notes, and snippets.

@chrisobriensp
Created December 25, 2012 21:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisobriensp/4375519 to your computer and use it in GitHub Desktop.
Save chrisobriensp/4375519 to your computer and use it in GitHub Desktop.
Shows using the SP2013 JavaScript Client Object Model (JSOM) to call the search REST API
function getSearchResultsUsingREST(queryText) {
// search can use the app web URL as the base, so no need to use SP.AppContextSite(@target) to access the host web..
var searchUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryText + "'";
var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);
executor.executeAsync(
{
url: searchUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: onGetSearchResultsSuccess,
error: onGetSearchResultsFail
}
);
}
function onGetSearchResultsSuccess(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
if (results.length == 0) {
$('#related-content-results').text('No related documents were found');
}
else {
var searchResultsHtml = '';
$.each(results, function (index, result) {
searchResultsHtml += "<a target='_blank' href='" + result.Cells.results[6].Value + "'>" + result.Cells.results[3].Value + "</a> (" + result.Cells.results[10].Value + ")<br />";
});
$('#related-content-results').html(searchResultsHtml);
}
}
function onGetSearchResultsFail(data, errorCode, errorMessage) {
$('#related-content-results').text('An error occurred whilst searching for related content - ' + errorMessage);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment