vef1-2024

Vefforritun 1 kennd haustið 2024

View the Project on GitHub vefforritun/vef1-2024

Fyrirlestur – Ajax

Vefforritun 1 — TÖL107G

Ólafur Sverrir Kjartansson, osk@hi.is


JSON


Munur á JSON og JS hlutum


JSON dæmi

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  }
}

JSON útfærslur


const obj = {
  a: 1,
  string: 'Halló, heimur',
  obj: {
    c: [1, 2, 3],
  },
};
const json = JSON.stringify(obj);
// "{"a":1,"string":"Halló, heimur","obj":{"c":[1,2,3]}}"
const back = JSON.parse(json);

try {
  JSON.parse('{');
} catch (e) {
  console.log(e);
}

// SyntaxError: Unexpected end of JSON input


Ajax


Ajax skýringarmynd


XMLHttpRequest


fetch


fetch notkun



fetch('url')
  .then((result) => {
    if (!result.ok) {
      throw new Error('Non 200 status');
    }
    return result.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

eða með async await

async function fetchData() {
  try {
    const result = await fetch(url);

    if (!result.ok) {
      throw new Error('result not ok');
    }

    return await result.json();
  } catch (e) {
    console.warn('unable to fetch', e);
    return null;
  }
}

const options = {
  body: { /* object af post data */ },
  cache: '', /* cache header */
  headers: { /* auka headers */ },
  method: 'POST',
};

fetch('url', options);


Vefþjónustur



REST


Same-origin og CORS



Cross-origin resource sharing (CORS)





Að vinna með URL


const s = `
  http://user:pass@www.example.org/a/b
  ?foo=bar&bar=baz#hash`;
const url = new URL(s);
console.log(url);
{
  "origin": "http://www.example.org",
  "protocol": "http:",
  "username": "user",
  "host": "www.example.org",
  "pathname": "/a/b",
  "search": "?foo=bar&bar=baz",
  "hash": "#hash"
  // 
}

const qs = 'category=teaching&foo=bar';
const params = new URLSearchParams(qs);

params.set('name', 'Óli');
params.delete('foo');

console.log(params.toString());
// category=teaching&nafn=%C3%B3li



Stöður

Þegar gögn eru sótt yfir vefþjónustu getum við lent í mismumandi stöðum: