2018.1

Table Of Contents
Retrieving content
Depending on the type of content that the remote server returns - HTML or JSON - you can use
loadhtml(location) or loadjson(location) (see also: "loadhtml()" on page1067 and
"loadjson()" on page1070) to retrieve the content. The link that you selected in Step 1 should
be passed to the function as a string. For example:
loadjson('https://blog.mozilla.org/wp-json/wp/v2/posts?per_
page=5');
If the returned content is JSON data, that data has to be wrapped in HTML before inserting it
into the template. This is demonstrated in the example below.
Tip
Install the Postman application to preview JSON returned by an endpoint.
Inserting content in the template
To insert the content after the selected element, use results.after(). To replace the element
with the new content, use results.html() or results.replaceWith().
Example: recent posts
The following script loads five posts from Mozilla's blog and inserts their titles as links in a
template. Mozilla's blog is a WordPress website. Since the WordPress REST API uses JSON
as the response format, the loadjson() function has to be used and the received content has to
be wrapped in HTML.
If the script's selector was h1 (a level one heading), the retrieved content would be inserted after
each level one heading.
var postsObj = loadjson('https://blog.mozilla.org/wp-
json/wp/v2/posts?per_page=5');
var html = '';
html = '<ul>';
for (var idx in postsObj) {
html += '<li><a href="' + postsObj[idx].link + '">' + postsObj
[idx].title.rendered + '</a></li>';
}
Page 710