This below code demonstrates how to query search using the SharePoint 2013 REST.
See Steps:
- Create a Separate page and a content editor Web part.
- Add the Below Code.
- I simply add a text box, a button, and a div to hold the results.
- Enter the query, click the button, and then see search results.
- <html>
-
- <head>
-
- <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
-
- <div>
-
- <label for="searchTextBox">Search: </label>
-
- <input id="TextBox" type="text" />
-
- <input id="Button" type="button" value="Search" />
-
- </div>
-
- <div id="resultsDiv"></div>
-
- <script type="text/javascript">
-
- var context = SP.ClientContext.get_current();
-
- $(document).ready(function () {
-
- var spAppWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
-
- $("#Button").click(function () {
-
- var queryUrl = spAppWebUrl + "/_api/search/query?querytext='" + $("#TextBox").val() + "'";
-
- $.ajax({ url: queryUrl, method: "GET", headers: { "Accept":"application/json; odata=verbose" }, success: onQuerySuccess, error: onQueryError });
-
- });
-
- });
-
- function onQuerySuccess(data) {
-
- var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
-
- $("#resultsDiv").append('<table>');
-
- $.each(results, function () {
-
- $("#resultsDiv").append('<tr>');
-
- $.each(this.Cells.results, function () {
-
- $("#resultsDiv").append('<td>' + this.Value + '</td>');
-
- });
-
- $("#resultsDiv").append('</tr>');
-
- });
-
- $("#resultsDiv").append('</table>');
-
- }
-
- function onQueryError(error) {
-
- $("#resultsDiv").append(error.statusText)
-
- }
-
-
-
- function getQueryStringParameter(urlParameterKey) {
-
- var params = document.URL.split('?')[1].split('&');
-
- var strParams = '';
-
- for (var i = 0; i < params.length; i = i + 1) {
-
- var singleParam = params[i].split('=');
-
- if (singleParam[0] == urlParameterKey)
-
- return decodeURIComponent(singleParam[1]);
-
- }
-
- }
-
- </html>
-
- </head>