Basic Usage

- const xhr = new XMLHttpRequest();
- xhr.onload = function () {
- console.log(this.responseText);
- }
- xhr.onerror = function () {
- console.log("Ups something error")
- }
- xhr.onload = () => {
- // akan menyebabkan error, karena arrow function tidak memiliki this.
- console.log(this.responseText);
- }
- xhr.open("GET", "https://api-to-call.com/endpoint");
- xhr.send();
- const xhr = new XMLHttpRequest();
- xhr.onload = function () {
- console.log(this.responseText)
- }
- xhr.onerror = function () {
- console.log("Ups something error")
- }
- xhr.open("GET", "https://web-server-book-dicoding.appspot.com/list");
- xhr.send();
- JSON.parse(this.responseText)
Anda juga bisa mencoba menjalankan potongan kode di atas pada repl.it melalui tautan berikut: https://repl.it/@dicodingacademy/163-06-AJAX-XHR-basic?lite=true
Header and Body Request using XHR
Set Header Property
- const xhr = new XMLHttpRequest();
- xhr.onload = function() {
- console.log(this.responseText);
- }
- xhr.onerror = function() {
- console.log("Ups something error");
- }
- xhr.open("POST", "https://web-server-book-dicoding.appspot.com/add");
- // menambahkan properti pada header request
- xhr.setRequestHeader("Content-Type", "application/json");
- const xhr = new XMLHttpRequest();
- xhr.onload = function() {
- console.log(this.responseText);
- }
- xhr.onerror = function() {
- console.log("Ups something error");
- }
- xhr.open("POST", "https://web-server-book-dicoding.appspot.com/add");
- // menambahkan properti pada header request
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.setRequestHeader("X-Auth-Token", "12345")
Set Data to Body Request
- const xhr = new XMLHttpRequest();
- xhr.onload = function() {
- console.log(this.responseText);
- }
- xhr.onerror = function() {
- console.log("Ups something error");
- }
- xhr.open("POST", "https://web-server-book-dicoding.appspot.com/add");
- // menambahkan properti pada header request
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.setRequestHeader("X-Auth-Token", "12345")
- const book = {
- id: 10,
- title: "Edensor",
- author: "Andrea Hirata"
- }
- xhr.send(JSON.stringify(book));
Hasil Akhir Cek :
https://github.com/dicodingacademy/a163-bfwd-labs/tree/302-dicoding-books-xhr







Komentar (0)
Mari berdiskusi dengan sehat. Hindari kata-kata kasar dan provokasi.
Belum ada komentar. Jadilah yang pertama!