← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 14 of 26

JS AJAX रिस्पॉन्स

किसी AJAX request के पूरा होने पर, response को सही format में पढ़ना ज़रूरी है -- plain text, JSON, या कभी-कभी XML -- और इसके contents पर भरोसा करने से पहले response के status और headers जांचने ज़रूरी हैं, क्योंकि एक completed request अपने आप एक successful request नहीं होती।
Syntax
javascript
xhr.responseText
xhr.responseXML
xhr.status
xhr.getResponseHeader("name");

एक JSON Response पढ़ना

response.json() response body को JSON के रूप में parse करता है और parsed JavaScript value में resolve होने वाला एक Promise return करता है -- structured API responses पढ़ने का सबसे आम तरीका, क्योंकि ज़्यादातर modern APIs डिफ़ॉल्ट रूप से JSON return करते हैं।

Note: response.json() के result को हमेशा await करें या .then() करें, क्योंकि body को parse करना खुद एक asynchronous operation है, कोई तुरंत synchronous operation नहीं।
Warning: किसी ऐसे response पर response.json() कॉल करना जिसकी body असल में valid JSON न हो (जैसे server से आया एक HTML error page) कुछ उपयोगी return करने के बजाय एक error throw करता है।

उदाहरण: Reading a JSON Response

javascript
// Define the method `fetch` taking `"data.php"`
// Define the method `fetch` taking `"data.php"`
fetch("data.php")
  // On success, run this with the resolved value as `response`
  // On success, run this with the resolved value as `response`
  .then(response => response.json())
  // On success, run this with the resolved value as `data`
  // On success, run this with the resolved value as `data`
  .then(data => console.log(data));

response.ok और Status जांचना

response.ok एक boolean है, जो सिर्फ तभी true होता है जब HTTP status 200-299 range में हो -- इसे (या सीधे response.status को) जांचना ज़रूरी है, क्योंकि fetch का promise एक 404 या 500 response के लिए भी सामान्य रूप से resolve होता है, किसी failed request से आपकी उम्मीद के उलट।

Note: fetch के resolve होते ही तुरंत response.ok जांचें, body को parse करने की कोशिश करने से पहले, ताकि बाद में confusing parse error देने के बजाय एक failed request जल्दी पकड़ ली जाए।
Warning: यह मान लेना कि एक resolved fetch promise का मतलब हमेशा success है, सबसे आम fetch-related bugs में से एक है -- एक HTTP error status भी promise को सफलतापूर्वक resolve कर देता है।

उदाहरण: Checking response.ok and Status

javascript
fetch("data.php").then(response => {
  console.log(response.ok, response.status); // check before trusting the data
  return response.json();
});

Text और दूसरे Response Formats पढ़ना

response.text() body को एक plain string के रूप में पढ़ता है, जो HTML fragments या plain-text responses के लिए उपयोगी है, जबकि response.blob() binary data (जैसे कोई image या file) पढ़ता है, हर एक एक Promise return करता है, ठीक response.json() की तरह।

Note: response-reading method को server द्वारा भेजे गए असली content से मिलाएं -- plain text या HTML के लिए .text(), JSON के लिए .json(), binary files के लिए .blob()।
Warning: असली response format के लिए गलत parsing method कॉल करना (जैसे किसी plain-text response पर .json()) बेकार errors या गड़बड़ data देता है।

उदाहरण: Reading Text and Other Response Formats

javascript
fetch("data.php").then(response => response.text()).then(text => console.log(text));

Response Headers पढ़ना

response.headers.get(headerName) response से एक खास header पढ़ता है, जो server द्वारा body के साथ भेजे गए metadata के लिए उपयोगी है -- जैसे format confirm करने के लिए Content-Type, या यह बताने वाले custom pagination headers कि कुल कितने results मौजूद हैं।

Note: हर चीज़ को response body में ही encode करने की कोशिश करने के बजाय, server द्वारा जानबूझकर body के बाहर दी गई metadata पढ़ने के लिए response.headers.get() इस्तेमाल करें।
Warning: .get() से पढ़ते समय header names case-insensitive होते हैं, पर किसी गायब लगने वाले header को debug करते समय यह भूलना आसान है।

उदाहरण: Reading Response Headers

javascript
fetch("data.php").then(response => {
  // Print `response.headers.get("Content-Type")` to the console
  // Print `response.headers.get("Content-Type")` to the console
  console.log(response.headers.get("Content-Type"));
});

Response Body सिर्फ एक बार पढ़ी जा सकती है

किसी response की body एक stream है जिसे सिर्फ एक बार consume किया जा सकता है -- एक ही response object पर response.json() और फिर response.text() कॉल करना दूसरी call पर fail हो जाता है, क्योंकि body पहले ही पढ़ी और drain की जा चुकी है।

Note: अगर आपको सच में किसी response body को एक से ज़्यादा बार पढ़ना है (दुर्लभ), तो original को consume करने से पहले उसे response.clone() से पहले clone करें।
Warning: पहले से consume हो चुकी response body को पढ़ने की कोशिश करना एक error देता है ("body stream already read"), जो इस one-time-use constraint को न जानने पर एक confusing message है।

उदाहरण: The Response Body Can Only Be Read Once

javascript
fetch("data.php").then(response => {
  return response.json().then(data => {
    console.log(data);
    // return response.text(); // would fail, body already read
  });
});
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी ऐसे response पर response.json() कॉल करना जो असल में JSON नहीं है (जैसे एक HTML error page), जो अनपेक्षित content return करने के बजाय एक parsing error throw करता है।
  2. यह भूल जाना कि fetch() का promise सिर्फ network failure पर reject होता है, किसी HTTP error status पर नहीं -- किसी 404 या 500 का पता लगाने के लिए response.ok को explicitly check करना ज़रूरी है।
  3. किसी fetch response body को एक से ज़्यादा बार पढ़ने की कोशिश करना -- body stream को हर response object के लिए सिर्फ एक बार consume किया जा सकता है।
चैप्टर सारांश
  • response.json(), response.text(), और response.blob() हर एक response body को अलग format में parse करते हैं, और हर एक एक Promise return करता है।
  • response.ok सिर्फ HTTP status codes 200-299 के लिए true होता है -- किसी response को successful मानने से पहले हमेशा इसे check करें।
  • response.headers.get(name) एक specific response header पढ़ता है, content type या pagination metadata के लिए उपयोगी।
ब्राउज़र सपोर्ट

fetch और XMLHttpRequest responses पढ़ना हर modern browser में समान रूप से काम करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.