2022.2

Table Of Contents
Tip: Selectanelement,thenclickon'ID'intheAttributespane,tocreateascriptthathasthatele-
ment'sIDasselector.
Retrieving content
Dependingonthetypeofcontentthattheremoteserverreturns-HTMLorJSON-youcanuseload-
html(location)orloadjson(location)(seealso:"loadhtml()"onpage1182and"loadjson()"
onpage1184)toretrievethecontent.ThelinkthatyouselectedinStep1shouldbepassedtothefunc-
tionasastring.Forexample:
loadjson('https://blog.mozilla.org/wp-json/wp/v2/posts?per_page=5');
IfthereturnedcontentisJSONdata,thatdatahastobewrappedinHTMLbeforeinsertingitintothe
template.Thisisdemonstratedintheexamplebelow.
Tip: InstallthePostmanapplicationtopreviewJSONreturnedbyanendpoint.
Tip: ToloadaJavaScriptfile(.js)orastylesheet(.css)youcanuseloadtext().See"loadtext
()"onpage1186.
Inserting content in the template
Toinsertthecontentaftertheselectedelement,useresults.after().Toreplacetheelementwith
thenewcontent,useresults.html()orresults.replaceWith().
Example: recent posts
ThefollowingscriptloadsfivepostsfromMozilla'sblogandinsertstheirtitlesaslinksinatemplate.
Mozilla'sblogisaWordPresswebsite.SincetheWordPressRESTAPIusesJSONastheresponse
format,theloadjson()functionhastobeusedandthereceivedcontenthastobewrappedinHTML.
Ifthescript'sselectorwash1(aleveloneheading),theretrievedcontentwouldbeinsertedaftereach
leveloneheading.
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>';
}
html += '</ul>';
results.after(html);
SeeWordPressRESTAPIdeveloperendpointreference.
Page 834