JS का AJAX XMLHttp
In this page:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this.responseText
}
};
xhr.open("GET", url);
xhr.send();
एक Request बनाना और Configure करना
new XMLHttpRequest() एक नया request object बनाता है, और .open(method, url, async) इसे एक HTTP method, target URL, और यह चाहिए कि यह asynchronously चले या नहीं (modern code में लगभग हमेशा true) के साथ configure करता है -- यह सिर्फ configuration है, इस point पर अभी कुछ भेजा नहीं गया है।
उदाहरण: Creating and Configuring a Request
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true); // configured, nothing sent yet
console.log(xhr.readyState); // 1 - opened
readyState Lifecycle
किसी request के आगे बढ़ने पर readyState पांच numeric values से गुज़रता है: 0 (uninitialized), 1 (opened), 2 (headers received), 3 (loading), और 4 (done) -- onreadystatechange event हर बार यह value बदलने पर fire होता है, जो आपको किसी भी stage पर react करने देता है, हालांकि खासतौर पर 4 जांचना सबसे आम pattern है।
उदाहरण: The readyState Lifecycle
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => console.log("readyState:", xhr.readyState)` to `xhr.onreadystatechange`
// Assign `() => console.log("readyState:", xhr.readyState)` to `xhr.onreadystatechange`
xhr.onreadystatechange = () => console.log("readyState:", xhr.readyState);
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();
HTTP Status Code जांचना
readyState के 4 तक पहुंचने पर, status property server द्वारा return किया गया असली HTTP status code रखती है -- success के लिए 200, not found के लिए 404, server error के लिए 500 -- और readyState के साथ इसे जांचना सच में सफल response को एक completed-but-failed response से अलग करने के लिए ज़रूरी है।
उदाहरण: Checking the HTTP Status Code
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => {` to `xhr.onreadystatechange`
// Assign `() => {` to `xhr.onreadystatechange`
xhr.onreadystatechange = () => {
// Check whether `xhr.readyState === 4`
// Check whether `xhr.readyState === 4`
if (xhr.readyState === 4) {
// Print `xhr.status === 200 ? "Success" : "Failed with status " + xhr.status` to the console
// Print `xhr.status === 200 ? "Success" : "Failed with status " + xhr.status` to the console
console.log(xhr.status === 200 ? "Success" : "Failed with status " + xhr.status);
}
};
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();
Request भेजना और Errors संभालना
.send() असल में configured request को भेजता है -- POST/PUT requests के लिए एक optional body argument के साथ -- और अलग onload/onerror event handlers (XMLHttpRequest में थोड़ा ज़्यादा modern addition) basic success/failure handling के लिए manually readyState जांचने का एक साफ विकल्प देते हैं।
उदाहरण: Sending the Request and Handling Errors
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => console.log("Loaded:", xhr.responseText)` to `xhr.onload`
// Assign `() => console.log("Loaded:", xhr.responseText)` to `xhr.onload`
xhr.onload = () => console.log("Loaded:", xhr.responseText);
// Assign `() => console.log("Request failed")` to `xhr.onerror`
// Assign `() => console.log("Request failed")` to `xhr.onerror`
xhr.onerror = () => console.log("Request failed");
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();
XMLHttpRequest बनाम fetch: एक सीधी तुलना
एक जैसी GET request को साथ-साथ रखना fetch के फायदे को साफ तौर पर उजागर करता है: कम lines, कोई manual readyState checking नहीं, और native promise chaining -- यही वजह है कि fetch नए code के लिए default recommendation बन गया है, जबकि XMLHttpRequest की जानकारी मुख्यतः legacy code के लिए उपयोगी बनी हुई है।
उदाहरण: XMLHttpRequest vs fetch: A Direct Comparison
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
// Declare the constant `xhr` as a new `XMLHttpRequest` instance
const xhr = new XMLHttpRequest();
// Assign `() => console.log(xhr.responseText)` to `xhr.onload`
// Assign `() => console.log(xhr.responseText)` to `xhr.onload`
xhr.onload = () => console.log(xhr.responseText);
// Call `xhr.open("GET", "data.php")`
// Call `xhr.open("GET", "data.php")`
xhr.open("GET", "data.php");
// Call `xhr.send()`
// Call `xhr.send()`
xhr.send();
// Call `fetch("data.php").then(r => r.text()).then(text => console.log(text))`
// Call `fetch("data.php").then(r => r.text()).then(text => console.log(text))`
fetch("data.php").then(r => r.text()).then(text => console.log(text));
- status check किए बिना सिर्फ readyState check करना, जो किसी failed request (जैसे 404) पर completion handler को ऐसे trigger कर सकता है जैसे वह succeed हुआ हो।
- गलत argument order के साथ .open() कॉल करना या बाद में .send() कॉल करना भूल जाना, request को configured तो रखते हुए लेकिन कभी actually भेजे बिना।
- .open() कॉल करने से पहले .setRequestHeader() से request headers set करना, जबकि इसे open() के बाद लेकिन send() से पहले कॉल किया जाना चाहिए।
- new XMLHttpRequest() एक request object बनाता है, .open(method, url) उसे configure करता है, और .send() असल में उसे fire करता है।
- readyState request के lifecycle stage को 0 (uninitialized) से 4 (complete) तक track करता है, आमतौर पर onreadystatechange के अंदर check किया जाता है।
- status response आने पर HTTP status code (जैसे 200 या 404) रखता है, और इसे readyState के साथ check किया जाना चाहिए।
XMLHttpRequest को 2000s की शुरुआत से हर browser में support मिला है और backward compatibility के लिए आज भी supported है।
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML