Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Accessing Apex REST from Site.com
@RestResource(urlMapping='/v1.0/messages')
global class MessageService {
@HttpGet
global static void getMessages() {
// buildMessages gets FeedItems
List<Message> messages = buildMessages();
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf( JSON.serialize(messages) );
}
// build messages implementation...
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '{!Site.messagesURL}',
success: function(response) {
var messageList = $('<ul></ul>');
$.each(response, function(idx, val) {
messageList.append(
'<li>' +
'Date: ' + val.messageDate + '<br />' +
'Title: ' + val.title + '<br />' +
'Body: ' + val.body + '<br />' +
'</li>'
);
});
$('#messages').html(messageList);
}
});
});
</script>
@RestResource(urlMapping='/v1.0/messages')
global class MessageService {
private static final String GROUP_ID = '<insert_your_chatter_groupid>';
@HttpGet
global static void getMessages() {
String callback = RestContext.request.params.get('callback');
// buildMessages gets FeedItems
List<Message> messages = buildMessages();
RestResponse res = RestContext.response;
// add in a CORS header response
// res.addHeader('Access-Control-Allow-Origin','https://sitepreview.gus.force.com');
res.addHeader('Access-Control-Allow-Origin','https://myown-developer-edition.gus.force.com');
res.addHeader('Content-Type', 'application/javascript');
res.responseBody = Blob.valueOf(callback + '(' + JSON.serialize(messages) + ')');
}
private static List<Message> buildMessages() {
List<Message> messages = new List<Message>();
for (FeedItem item : [
SELECT Title, Body, CreatedDate
FROM FeedItem
WHERE ParentId = :GROUP_ID
ORDER BY CreatedDate DESC
Limit 5
]) {
messages.add(new Message(item.CreatedDate.date(), item.Title, item.Body));
}
return messages;
}
class Message {
public Message(Date d, String t, String b) {
messageDate = d;
title = t;
body = b;
}
public Date messageDate { get; set; }
public String title { get; set; }
public String body { get; set; }
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '{!Site.messagesURL}',
dataType: 'jsonp',
success: function(response) {
var messageList = $('<ul></ul>');
$.each(response, function(idx, val) {
messageList.append(
'<li>' +
'Date: ' + val.messageDate + '<br />' +
'Title: ' + val.title + '<br />' +
'Body: ' + val.body + '<br />' +
'</li>'
);
});
$('#messages').html(messageList);
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.