Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Alternative Shorthand AJAX Methods in jQuery

Tech 1

The $.load() Method

jQuery's load() method is a straightforward yet powerful AJAX utility that fetches data from a server and injects the returned content directly into the matched DOM element. It uses a GET request by default, and automatically switches to POST when additional request parameters are provided.

Syntax:

$(targetSelector).load(targetUrl, requestData, completionCallback);

Parameter breakdown:

  • targetUrl: The endpoint URL to send the request to
  • requestData: Optional key-value data to send with the request
  • completionCallback: Optional callback function that executes after the content loads successfully

Example Implementation

Test page HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Load Method Test</title>
    <script src="assets/jquery.min.js"></script>
    <script>
        function loadContent() {
            // Example with parameters and callback:
            // $("#contentContainer").load("backend-endpoint.do", "user=test&pass=123", () => alert("Load complete"));
            $("#contentContainer").load("partial-content.html #skill-list");
        }
    </script>
</head>
<body>
    <div id="contentContainer" style="width: 150px; height: 180px; border: 1px solid #333;"></div>
    <button onclick="loadContent()">Test Load Method</button>
</body>
</html>

Partial content HTML to load:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Partial Content</title>
</head>
<body>
    <ul id="skill-list">
        <li>Java</li>
        <li>HTML</li>
        <li>CSS</li>
        <li>MySQL</li>
        <li>Python</li>
    </ul>
</body>
</html>

Back-end Servlet example:

package com.example.backend.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/backend-endpoint.do")
public class LoadHandlerServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        System.out.println("Received username: " + username);
        System.out.println("Received password: " + password);
        
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print("<h1>Hello from server</h1>");
    }
}

The $.get() Shorthand Method

$.get() is a simplified GET-based AJAX function that replaces the more verbose full $.ajax() configuration. It only runs a callback when the request succeeds, so use the full $.ajax() if you need error handling.

Syntax:

$.get(requestUrl, requestData, successCallback, responseDataType);

Parameter breakdown:

  • requestUrl: Target endpoint URL
  • requestData: Optional data to send with the request
  • successCallback: Callback function that runs on successful response
  • responseDataType: Expected format of the response: xml, html, script, json, text, or default

This method is just syntactic sugar for the full $.ajax() call, equivalent to:

$.ajax({
    type: 'GET',
    url: requestUrl,
    data: requestData,
    success: successCallback,
    dataType: responseDataType
});

The $.getJSON() Shorthand Method

JSON is a common, flexible data format for client-server communication that works natively with JavaScript. $.getJSON() is a specialized AJAX shorthand that automatically expects a JSON response, and it allso supports cross-domain requests.

Syntax:

$.getJSON(requestUrl, requestData, successCallback);

Parameters:

  • requestUrl: Target endpoint URL
  • requestData: Optional request parameters
  • successCallback: Optional callback for successful resposne

This is equivalent to the following full $.ajax() configuration:

$.ajax({
    url: requestUrl,
    data: requestData,
    success: successCallback,
    dataType: 'json'
});

Unlike generic $.get(), $.getJSON() supports cross-domain requests by supporting JSONP callback patterns: you can append a callback=myFunction query parameter to the URL to enable JSONP handling. Note that $.getJSON() always uses the GET method, so if you need to send large payloads, use $.post() instead.


The $.post() Shorthand Method

$.post() is the POST equivalent of $.get(), a simplified AJAX method that replaces the full $.ajax() configuration for POST requests. It only runs a callback on success, so use full $.ajax() if you need error handling.

Syntax:

$.post(requestUrl, requestData, successCallback, responseDataType);

Parameter breakdown:

  • requestUrl: Target endpoint URL
  • requestData: Optional data to send with the request
  • successCallback: Callback function that runs on successful response
  • responseDataType: Expected format of the response: xml, html, script, json, text, or default

This shorthand is equivalent to:

$.ajax({
    type: 'POST',
    url: requestUrl,
    data: requestData,
    success: successCallback,
    dataType: responseDataType
});

Example Usage

Front-end test page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX Shorthand Test</title>
    <script src="assets/jquery.min.js"></script>
    <script>
        function runAllTests() {
            // Test $.get()
            $.get(
                "student-data.do",
                {"username": "zhangsan", "password": "123456"},
                (studentList) => {
                    $.each(studentList, (index, student) => {
                        console.log(student);
                    });
                },
                "json"
            );

            console.log("--- End of $.get test ---");

            // Test $.getJSON()
            $.getJSON(
                "student-data.do",
                {"username": "zhangsan", "password": "123456"},
                (studentList) => {
                    $.each(studentList, (index, student) => {
                        console.log(student);
                    });
                }
            );

            console.log("--- End of $.getJSON test ---");

            // Test $.post()
            $.post(
                "student-data.do",
                {"username": "zhangsan", "password": "123456"},
                (studentList) => {
                    $.each(studentList, (index, student) => {
                        console.log(student);
                    });
                },
                "json"
            );
        }
    </script>
</head>
<body>
    <button onclick="runAllTests()">Run All Tests</button>
</body>
</html>

Back-end Servlet for JSON response:

package com.example.backend.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.example.backend.pojo.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

@WebServlet("/student-data.do")
public class StudentDataServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        // Log incoming request data
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        
        // Generate sample student data
        Student stu1 = new Student("Bob", "Male", 20, new Date());
        Student stu2 = new Student("Alice", "Female", 21, new Date());
        Student stu3 = new Student("Charlie", "Male", 19, new Date());
        Student stu4 = new Student("Diana", "Female", 22, new Date());
        
        ArrayList<Student> studentList = new ArrayList<>();
        Collections.addAll(studentList, stu1, stu2, stu3, stu4);
        
        // Format date and convert to JSON
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd");
        Gson gson = gsonBuilder.create();
        String jsonResponse = gson.toJson(studentList);
        
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(jsonResponse);
    }
}
Tags: jQuery

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.