@inherits Custom.Hybrid.Razor14
@{
// Tell the page that we need the 2sxc Js APIs
Kit.Page.Activate("2sxc.JsCore");
}
<!-- unimportant stuff, hidden -->
Very basic WebApi Examples In this... <!-- unimportant stuff, hidden -->
<button type="button" class="btn btn-primary" onclick="helloFetchJson(this)">Quick Fetch Json "Hello"</button>
<script>
// Fetch using modern Browser Fetch-promises, with auto-get Json
// This is the recommended method if you expect JSON, because it's simpler
// This also uses the shortest API syntax `controller/method`
function helloFetchJson(moduleContext) {
$2sxc(moduleContext).webApi.fetchJson('basic/hello')
.then(data => alert('Result using quick Fetch JSON: ' + data));
}
</script>
<button type="button" class="btn btn-primary" onclick="helloFetch(this)">Quick Fetch "Hello"</button>
<script>
// Fetch using modern Browser APIs
// This is the more manual method, in case you don't expect JSON or want more control
// This uses the full internal syntax `app/auto/api/controller/method`
function helloFetch(moduleContext) {
$2sxc(moduleContext).webApi.fetch('app/auto/api/basic/hello')
.then(response => response.json())
.then(data => alert('Result using quick Fetch: ' + data));
}
</script>
<button type="button" class="btn btn-primary" onclick="helloFetchManual(this)">Quick Fetch "Hello"</button>
<script>
// Manual Fetch call using more code
// This is the most manual method, but shows how it actually works internally
function helloFetchManual(moduleContext) {
var moduleApi = $2sxc(moduleContext).webApi; // webApi for this specific Module
var fullApiUrl = moduleApi.url('app/auto/api/basic/hello'); // API url based on current App
var headers = moduleApi.headers("GET"); // Headers used for GET calls
fetch(fullApiUrl, { headers: { ...headers } })
.then(response => response.json())
.then(data => alert('Result using manual Fetch: ' + data));
}
</script>
<button type="button" class="btn btn-secondary" onclick="helloJQuery(this)">jQuery Get Hello</button>
<script>
// jQuery versions (not recommended any more, will not work on pages without jQuery)
function helloJQuery(moduleContext) {
$2sxc(moduleContext).webApi.get('app/auto/api/basic/hello')
.then(function (results) {
alert("Result using jQuery: " + results);
});
}
</script>
<button type="button" class="btn btn-primary" onclick="squareFetch(this, 7)">Fetch Square 7</button>
<button type="button" class="btn btn-primary" onclick="squareFetch(this, 27)">Fetch Square 27</button>
<script>
function squareFetch(moduleContext, original) {
$2sxc(moduleContext).webApi.fetchJson('basic/square?number=' + original)
.then(data => alert('The square of ' + original + '= ' + data));
}
</script>
<!-- unimportant stuff, hidden -->