Dojo AJAX Request to Retrieve REST Service Data and Display the Results on the Page

dojo.xhr.get({
  url:"REST.xsp/People",
  handleAs:"json",
  load: function(data){
    var output = '<table>';
 
    // Build the header row by inspecting column names
    output += '<tr>';
    for (var col in data[0]) {
        output += '<th>' + col + '</th>';
    }
    output += '</tr>';
 
    // Build the data rows
    for(var i in data){
      output += '<tr>';
      for (col in data[i]) {
        output += '<td>' + data[i][col] + '</td>';
      }
      output += '</tr>';
    }
    output += '</table>';
    dojo.byId('resultsDiv').innerHTML = output;
  },
  error: function(msg, args) {
    dojo.style('resultsDiv', 'color', 'red');
    dojo.byId('resultsDiv').innerHTML = 'Status: ' + args.xhr.status + '<br />' + msg;
  }
});
 





This snippet demonstrates how to use a Dojo AJAX call to retrieve data from a REST service and display the data on an XPage.

If the request is successful, it inspects the results of the REST service and writes out a table with the column names coming from the REST service columns and the data coming from the REST service JSON. If the request is not successful, it writes an error message onto the page instead.

In order to use it, you must have a REST service set up (in this example, it was a viewJsonService REST service on a page named REST.xsp with the pathInfo property set to People) and a <div> tag where the information will be written (in this example, the passthrough HTML <div> tag has an ID of resultsDiv).

For more information, see this blog post:   http://xcellerant.net/dojo-in-xpages-20-ajax-callbacks/

JavaScript (Client)
Brad Balassaitis
April 29, 2014 9:53 AM
Rating
37

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



No comments yetLogin first to comment...