null
Sample JSON:
{
"firstName": "Jane",
"lastName": "Smith",
"address": {
"streetAddress": "425 2nd Street",
"city": "San Francisco",
"state": "CA",
"postalCode": 94107
},
"phoneNumbers": [
"212 732-1234",
"646 123-4567" ]
}
var myProfile =
{"firstName": "Liz",
"lastName": "Howard",
"cats": ["Tribbles", "Jean Claws"]};
var p = document.createElement('p');
p.innerHTML = 'My name is ' + myProfile.firstName + ' ' + myProfile.lastName + '. ';
p.innerHTML += 'My cats are ' + myProfile.cats.join(', ') + '.';
var p = $('<p>');
p.html('My name is ' + myProfile.firstName + ' ' + myProfile.lastName + '. ');
p.append('My cats are ' + myProfile.cats.join(', ') + '.');
Pair with the person(s) next to you to work through it together.
= Asynchronous JavaScript and "XML"
What else?
Technologies Used: | Technologies Used: |
|
|
// instantiate a new request
var request = new XMLHttpRequest();
// add event listeners
request.addEventListener('load', function () {
// transform a string into a usable object
console.log(JSON.parse(request.responseText));
});
request.open('get', '/path/to/api', true);
request.setRequestHeader('Content-type', 'application/json');
request.send();
Use the jQuery $.ajax function.
$.ajax({type: "GET",
url: "filename.json",
dataType: "json",
success: function(data) { },
error: function(xhr, status, e) { }
});
$.ajax({type: "GET",
url: "https://api.myjson.com/bins/wgonb",
dataType: "json",
success: function(response) {
var books = response.books;
for (var i = 0; i < books.length; i++) {
var book = books[i];
var p = $('<p>');
p.html(book.title + ' by ' + book.author);
$('body').append(p);
}
},
error: function(xhr, status, e) {
console.log(status, e);
}
});
JSBin
It will teach you so much about what's in requests and responses. Google everything you don't understand.
Pair with the person(s) next to you to work through it together.
$.ajax({type: "GET",
url: "/api/books",
dataType: "json",
data: {'sortBy': 'author'},
success: processBooks
});
$.ajax({type: "POST",
url: "/api/book/new",
dataType: "json",
data: {'title': 'I, Robot', 'author': 'I. Asimov'}
success: processBoooks
});
UI No-Nos:
For http://store.company.com/dir/page.html: