Reputation: 544
I use jQuery frequently but I have realized that I need to understand the underlying Javascript better. I have worked out the AJAX part but am stuck on the nested functions. Any help is greatly appreciated.
document.onreadystatechange = function() {
var state = document.readyState;
if (state == 'interactive') {
$('#button').on("click", function() {
$.getJSON(apiurl, function(json) {
$.each(json.photos.photo, function(i, myresult) {
apiurl_size = "https//api/myresult";
$.getJSON(apiurl_size, function(size) {
$.each(size.sizes.size, function(i, myresult_size) {
if (myresult_size.width == selected_size) {
$("#results").append('<p class="col-md-4"><a href="" ><img src="' + myresult_size.source + '"/></a></p>');
}
})
})
});
});
});
} else if (state == 'complete') {
document.getElementById('complete');
}
}
What I want to know:
how to grab the id selector in $('button')
since document.getElementById('button')
returns the entire element but I cannot enact the .on click
functionalitiy
breaking the .getJSON
function out into a pure JS reusable function
Upvotes: 0
Views: 49
Reputation: 780798
$("#button").on("click", cb_function)
is analogous to document.getElementById("button").addEventListener("click", cb_function)
. If you were using a selector that can match multiple elements, it's similar except that it loops over all the returned elements to add event listeners to all of them.
$.getJSON(URL, cb_function)
creates an AJAX request to the URL whose onreadystatechange
callback function essentially does:
JSON.parse()
on the response.cb_function
with the result of the parse.A simple version would be like:
function getJSON(url, cb_function) {
var xhr = new XMLHTTPRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if (xhr.readystate == 4 && xhr.status == 200) {
cb_function(JSON.parse(xhr.responseText));
}
}
xhr.send();
return xhr;
}
The real $.getJSON
allows you to supply parameters to the URL, and it automatically converts from an object to the appropriate URL-encoded string to add as URL parameters. But neither of your calls has data parameters, so this definition should work for you.
Upvotes: 1