how can i fetch the api in javascript data code example
Example 1: get data from fetch api into variable
<script>
function getFromAPI(url, callback){
var obj;
fetch(url)
.then(res => res.json())
.then(data => obj = data)
.then(() => callback(obj))
}
getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);
function getData(arrOfObjs){
var results = "";
arrOfObjs.forEach( (x) => {
results += "<p> Id: " + x.id + "<ul>"
Object.keys(x).forEach( (p) => {
results += "<li>" + (p + ": " + x[p]) + "</li>";
});
results += "</ul> </p> <hr>"
})
results += "";
document.getElementById("myDiv").innerHTML = results;
}
</script>
Example 2: $_GET data using javascript
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
console.log($_GET("myvariable"));