get() से HTTP GET
In this page:
$.get(url, data, function (response) {
// handle response
}, dataType);
get() क्या है?
$.get() एक GET-style AJAX request बनाने का shorthand है, जो अक्सर server-side कुछ भी modify किए बिना server से data पढ़ने के लिए इस्तेमाल होता है।
उदाहरण: What is get()?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.get("data.php", function(data) {
console.log(data);
});
</script>
</body>
</html>
Query Parameters के साथ GET
GET requests URL में appended query parameters के रूप में data भेज सकती हैं, और jQuery pass किए गए plain object से उस query string को automatically बना सकता है।
उदाहरण: GET with Query Parameters
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.get("data.php", {category: "books", limit: 5}, function(data) {
console.log(data);
});
</script>
</body>
</html>
GET Success Callback
success callback server द्वारा return किया गया data receive करता है, जिसे आप फिर page को jQuery से update करने के लिए इस्तेमाल कर सकते हैं -- कोई list populate करना, कुछ भरना।
उदाहरण: GET Success Callback
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"></ul>
<script>
$.get("data.php", function(data) {
$("#list").append("<li>" + data.message + "</li>");
});
</script>
</body>
</html>
GET Error Handling
एक GET request network issues या किसी server error की वजह से fail हो सकती है, और request पर .fail() chain करना आपको उस case को cleanly handle करने देता है बजाय इसे unhandled छोड़ने के।
उदाहरण: GET Error Handling
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.get("data.php").done(function(data) {
console.log(data);
}).fail(function() {
console.log("Request failed");
});
</script>
</body>
</html>
एक छोटा GET Project
get() method simple read-only requests के लिए एक अच्छा choice है, जैसे items की एक list fetch करना या status check करना, क्योंकि यह code को $.ajax() से shorter रखता है।
उदाहरण: Small GET Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="checkStatus">Check Status</button>
<script>
$("#checkStatus").on("click", function() {
$.get("data.php", function(data) {
console.log("Status:", data.status);
});
});
</script>
</body>
</html>
const data = $.get("data.php")लिखना औरdataको response की तरह इस्तेमाल करना, जबकि यह एक jqXHR object है और असली data callback में आता है।"data.php?name=" + nameजैसे हाथ से query string बनाना बिना encoding के, जबकि{ name: name }जैसा एक object pass करना jQuery को इसे सही से encode करने देता है।- यह उम्मीद करना कि
$.get()किसी दूसरे domain की file के लिए काम करेगा, जबकि browser की same-origin policy इसे CORS के बिना block कर देती है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: