[{
"url":"https://flickr.com/bilde1.jpg",
"title":"Fint bilde av en bekker"
},{...}]
---
# Laste data
```javascript
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
console.log(data);
} else {
console.log('There was a problem with the request.');
}
}
}
httpRequest.open('GET', 'http://localhost:6000/sok?tag=bekk'); // Setter opp request
httpRequest.send(); // Sender request
```
---
# Laste data
```javascript
fetch('http://localhost:6000/sok?tag=bekk')
```
---
# Laste data
```javascript
fetch('http://localhost:6000/sok?tag=bekk').then(function(response) {
// her kan du gjøre noe med responsen
});
```
---
class: cols two
# JavaScript Object Notation - JSON
--
.col[
## JSON
```json
{
"string": "en string",
"key2": 1.2,
"boolean": false,
"array": [1,2,3,4,5,6],
"object": {
"key": "value"
},
"empty": null
}
```
]
.col[
## JavaScript objekter
```javascript
{
string: "en string",
key2: 1.2,
boolean: false,
array: [1,2,3,4,5,6],
object: {
key: "value"
},
empty: undefined
}
```
]
---
# Parse JSON
```javascript
JSON.parse('{"key":"value"}'); // {key: "value"}
```
--
```javascript
JSON.stringify({key:"value"}); // '{"key": "value"}'
```
---
# Parse reposonsen
## JSON
```javascript
fetch('http://localhost:6000/sok?tag=bekk').then(function(response) {
return response.json();
});
```
--
## Text
```javascript
fetch('http://localhost:6000/sok?tag=bekk').then(function(response) {
return response.text();
});
```
--
## Blob
```javascript
fetch('http://localhost:6000/sok?tag=bekk').then(function(response) {
return response.blob();
});
```
---
# Laste data
```javascript
fetch('http://localhost:6000/sok?tag=bekk').then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
```
--
```
[{
"url":"https://flickr.com/bilde1.jpg",
"title":"Fint bilde av en bekker"
},{
"url":"https://flickr.com/bilde2.jpg",
"title":"Ikke fullt så fint bilde av en bekker"
},{
"url":"https://flickr.com/bilde3.jpg",
"title":"Rart bilde av en bekk"
},{
...
}]
```
---
# Laste data
```javascript
fetch('http://localhost:6000/sok?tag=bekk').then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(error) {
throw error;
});
```
---
# Same origin policy
```javascript
fetch('https://uit.no');
```
--
You will receive an error. `XMLHttpRequest` cannot load https://uit.no. No `'Access-Control-Allow-Origin'` header is present on the requested resource. Origin http://localhost:6000 is therefore not allowed access.
--
An origin is defined as a combination of URI scheme, hostname, and port number.
---
# Same origin policy