JSON server bilan ishlash
fetch() metodi
JSON ko‘pincha fayllarda saqlanadi yoki veb-serverlarga yuborilgan so‘rovlar orqali qaytariladi.
JavaScript JSON-ni yuklashi va uni JavaScript qiymatlariga aylantirishi mumkin.
JSON’ni yuklashning zamonaviy usuli — fetch() metodi.
Ushbu bob siz fetch() bilan tanish ekaningizni nazarda tutadi.
Agar tanish bo‘lmasangiz, JavaScript Fetch API darsligini ko‘ring.
JSON fayli
JSON fayllari odatda .json kengaytmasiga ega bo‘ladi.
JSON’ni yuklash
JSON faylini so‘rash uchun fetch() metodidan foydalaning.
response.json() metodi JSON matnini parse qiladi va JavaScript qiymatini qaytaradi.
Misol
async function loadJSON() {
const response = await fetch("customer.json");
const customer = await response.json();
myDisplayer(customer.name);
}
loadJSON();
O‘zingiz sinab ko‘ring »
JSON massivini yuklash
Agar faylda JSON massivi bo‘lsa, response.json() JavaScript massivini qaytaradi.
products.json
[
{"name":"Laptop","price":899},
{"name":"Mouse","price":29},
{"name":"Keyboard","price":79}
]
O‘zingiz sinab ko‘ring »
Misol
async function loadProducts() {
const response = await fetch("products.json");
const products = await response.json();
myDisplayer(products[0].name);
myDisplayer(products[0].price);
}
loadProducts();
O‘zingiz sinab ko‘ring »
Xatolarni tekshirish
fetch() metodi 404 kabi HTTP xatolari uchun xato chiqarmaydi.
JSON faylini o‘qishdan oldin ok va holat xususiyatlarini tekshiring.
Misol
async function loadJSON(file) {
const response = await fetch(file);
myDisplayer(response.ok);
myDisplayer(response.status);
const customer = await response.json();
myDisplayer(customer.name);
}
loadJSON("customer.json");
O‘zingiz sinab ko‘ring »
Xatolarni qayta ishlash
Yuklash xatolarini qayta ishlash uchun try...catch’dan foydalaning.
Misol
async function loadJSON(file) {
try {
const response = await fetch(file);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const customer = await response.json();
myDisplayer(customer.name);
}
catch(err) {myDisplayer(err.message)}
}
loadJSON("customer.json");
O‘zingiz sinab ko‘ring »
Bir nechta JSON faylini yuklash
Bir-biriga bog‘liq bo‘lmagan yuklashlar parallel bajarilishi mumkin.
Misol
// Async function to download files
async function loadData() {
const [customerResponse, productsResponse, newsResponse] = await Promise.all([
fetch("customer.json"),
fetch("products.json"),
fetch("news.json")
]);
const customer = await customerResponse.json();
const products = await productsResponse.json();
const news = await newsResponse.json();
myDisplayer("Custome name: " + customer.name);
myDisplayer(products.length + " products");
myDisplayer(news.length + " news items");
}
// Call the async function
loadData();
O‘zingiz sinab ko‘ring »
JSON yuborish
fetch() metodi veb-serverga JSON yuborishi ham mumkin.
Yangi ma’lumotlarni yuborish uchun POST metodidan foydalaning.
JavaScript obyektini JSON.stringify() yordamida JSON matniga o‘giring.
Misol
const person = {
name: "John",
age: 30
};
const response = await fetch("/api/person", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(person)
});
So‘rov parametrlari
fetch() ning ikkinchi argumenti so‘rov variantlarini o‘z ichiga oladi.
| Option | Tavsif |
|---|---|
| method | HTTP so‘rov metodi, masalan, POST. |
| headers | So‘rov haqida qo‘shimcha ma’lumot. |
| body | So‘rov bilan yuborilgan ma’lumotlar. |
Content-Type sarlavhasi
Content-Type sarlavhasi serverga qaysi turdagi ma’lumotlar yuborilayotganligini bildiradi.
Misol
headers: {
"Content-Type": "application/json"
}
So‘rov tanasi
So‘rov tanasi JavaScript obyektini emas, matnni o‘z ichiga olishi kerak.
Obyektni JSON matniga o‘girish uchun JSON.stringify()’dan foydalaning.
Misol
body: JSON.stringify(person)
Server javobini o‘qish
Server so‘rovni qabul qilgandan keyin JSON qaytarishi mumkin.
Qaytarilgan JSON’ni o‘qish uchun response.json()’dan foydalaning.
Misol
const person = {
name: "John",
age: 30
};
const response = await fetch("/api/person", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(person)
});
const result = await response.json();
document.getElementById("demo").textContent = result.message;
Javobni tekshirish
fetch() metodi 404 yoki 500 kabi HTTP xatolari uchun o‘z Promise’ini reject qilmaydi.
Javobni o‘qishdan oldin response.ok xususiyatini tekshiring.
Misol
const response = await fetch("/api/person", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(person)
});
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const result = await response.json();
Xatolarni qayta ishlash bilan JSON yuborish
So‘rov va javob xatolarini qayta ishlash uchun try...catch’dan foydalaning.
Misol
async function sendPerson() {
const person = {
name: "John",
age: 30
};
try {
const response = await fetch("/api/person", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(person)
});
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const result = await response.json();
document.getElementById("demo").textContent =
result.message;
}
catch (error) {
document.getElementById("demo").textContent =
error.message;
}
}
sendPerson();
To‘liq misol
Ushbu misol forma ma’lumotlarini serverga JSON sifatida yuboradi.
Misol
<input id="name" value="John">
<input id="age" type="number" value="30">
<button onclick="sendPerson()">Send</button>
<p id="demo"></p>
<script>
async function sendPerson() {
const person = {
name: document.getElementById("name").value,
age: Number(document.getElementById("age").value)
};
try {
const response = await fetch("/api/person", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(person)
});
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const result = await response.json();
document.getElementById("demo").textContent =
result.message;
}
catch (error) {
document.getElementById("demo").textContent =
error.message;
}
}
</script>
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
