jQuery $.getJSON() and $.getScript()
These two methods are further shortcuts in jQuery's AJAX toolkit. $.getJSON() fetches data specifically in JSON format. $.getScript() loads a JavaScript file from the server and executes it. Both keep your code short and focused.
$.getJSON() — Fetch JSON Data
JSON (JavaScript Object Notation) is the most popular data exchange format today. $.getJSON() is a shortcut for $.get() with dataType: "json". It automatically parses the response into a JavaScript object.
Syntax
$.getJSON(url, data, callback); // url → server URL that returns JSON // data → optional query parameters // callback → function(data, status, xhr)
Basic $.getJSON() Example
$(document).ready(function() {
$.getJSON("employees.json", function(data) {
$.each(data, function(i, emp) {
var row = "<tr><td>" + emp.id + "</td>" +
"<td>" + emp.name + "</td>" +
"<td>" + emp.department + "</td></tr>";
$("#empTable tbody").append(row);
});
});
});
Sample JSON File: employees.json
[
{ "id": 1, "name": "Priya Sharma", "department": "Development" },
{ "id": 2, "name": "Rahul Mehta", "department": "Design" },
{ "id": 3, "name": "Sneha Nair", "department": "Marketing" }
]
Diagram: $.getJSON() Flow
Browser → GET request → employees.json
│
Server returns JSON text:
[{"id":1,"name":"Priya",...},...]
│
jQuery auto-parses JSON into JS array
│
callback(data) runs with array as parameter
│
$.each(data) loops through each employee
│
Rows appended to table — no page reload
$.getJSON() with Query Parameters
// Fetch employees from a specific department
$.getJSON("api/employees.php", { dept: "Design" }, function(data) {
console.log(data.length + " designers found.");
$.each(data, function(i, emp) {
console.log(emp.name);
});
});
$.getJSON() with Error Handling
$.getJSON("data.json")
.done(function(data) {
console.log("Loaded:", data);
})
.fail(function(xhr, status, error) {
console.log("Error: " + status + " — " + error);
});
$.getScript() — Load and Run a JS File
The $.getScript() method fetches an external JavaScript file and executes it on the page. This is useful for loading optional scripts only when needed — keeping initial page load fast.
Syntax
$.getScript(url, callback); // url → path to the JavaScript file // callback → runs after the script loads and executes
Basic $.getScript() Example
$(document).ready(function() {
$("#loadChartBtn").click(function() {
$.getScript("js/chart.js", function() {
// chart.js is now loaded and ready to use
drawChart("#chartContainer");
});
});
});
The chart library only loads when the user clicks the button — not on every page load. This speeds up the initial experience.
Diagram: $.getScript() Lazy Loading
Page first loads:
─────────────────────────────────────────
index.html loads (fast — no chart.js)
User clicks "Show Chart" button:
─────────────────────────────────────────
$.getScript("chart.js") downloads chart.js
chart.js executes
callback fires → drawChart() runs → chart appears
Loading Multiple Scripts in Sequence
// Load script A first, then load script B after A is ready
$.getScript("js/libraryA.js", function() {
console.log("Library A ready");
$.getScript("js/libraryB.js", function() {
console.log("Library B ready");
initializeApp();
});
});
$.getScript() with Error Handling
$.getScript("js/plugin.js")
.done(function() {
console.log("Plugin loaded successfully.");
initPlugin();
})
.fail(function(xhr, status, error) {
console.log("Plugin failed to load: " + error);
});
Comparison: $.getJSON() vs $.getScript()
| Feature | $.getJSON() | $.getScript() |
|---|---|---|
| Fetches | JSON data | JavaScript (.js) file |
| Auto-parses | Yes — into a JS object | Yes — executes the JS |
| Use for | API responses, data files | Lazy-loading libraries/plugins |
| Callback receives | Parsed data object | Script text (rarely used) |
Practical: Load Quiz Questions Dynamically
$(document).ready(function() {
$("#startQuiz").click(function() {
$.getJSON("quiz-questions.json", function(questions) {
var html = "";
$.each(questions, function(i, q) {
html += "<div class='question'>";
html += "<p><strong>" + (i + 1) + ". " + q.question + "</strong></p>";
$.each(q.options, function(j, opt) {
html += "<label><input type='radio' name='q" + i + "' value='" + j + "'> " + opt + "</label><br>";
});
html += "</div>";
});
$("#quizArea").html(html);
});
});
});
Quick Summary
$.getJSON(url, data, callback)fetches and auto-parses JSON data.$.getScript(url, callback)downloads and executes an external JS file.- Both support promise-style
.done()and.fail()chaining. - Use
$.getScript()for lazy loading — load scripts only when they are needed. - Both are shortcuts built on
$.ajax()with preset options.
