Skip to content
Open
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules
*.*~
.*.swp
18 changes: 18 additions & 0 deletions ex8/js/ajax.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function ajax_get(url, callback) {
xmlhttp = new XMLHttpRequest();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing var statement.

xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What would happen is readyState!==4 or status!==200. Right now, nothing (your callback isn't called), which is probably not good.
You can simulate this by calling ajax_get in the console, or by a click of a button, after you have killed your local HTTP server.

console.log('responseText:' + xmlhttp.responseText);
try {
var data = JSON.parse(xmlhttp.responseText);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: while this is fine in javascript, it's customary (and mandatory in other languages) to move the var data outside of the try, because if the JSON.parse throws an error, data will remain undefined.
So you can do this instead:
var data = null; // or undefined; try{ data = JSON.parse(...) } . . . callback(data);

} catch(err) {
console.log(err.message + " in " + xmlhttp.responseText);
return;
}
callback(data);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you fine with the callback being called with undefined (if the responseText cannot be JSON-parsed? Maybe throw an error instead (or signal something else to the callback (two standard options: 1) have two callbacks - one for success - with data, one for failure - with some error message) 2) have a first param to the callback be error - if it's null, the next param is the parsed json)

}
};

xmlhttp.open("GET", url, true);
xmlhttp.send();
}
7 changes: 7 additions & 0 deletions ex8/js/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
requirejs.config({
baseUrl: 'js',
paths: {
ajax: 'ajax',
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should use requirejs' paths for other people's code, not yours.
This just alias updatePhoneBook to update. If you want it to be called update, rename the file; if you want it to be called updatePhoneBook, change the require call for it.

update: 'updatePhoneBook'
}
});
Loading