蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery 教程目录 40章
jQuery / LEARN BY DOING

jQuery get()/post() 方法

核对 HTTP GET 与 POST 请求语义差异,以及 jQuery $.get() 与 $.post() 的参数签名、数据类型解析与服务端表单转义回显实测。

学完这一章,你能够

  • 核对 HTTP GET 与 POST 请求语义差异,以及 jQuery $.get() 与 $.post() 的参数签名、数据类型解析与服务端表单转义回显实测。

HTTP 请求方法对比:GET 与 POST

客户端与服务器进行请求-响应通信时,最常用的两种 HTTP 方法是 `GET` 与 `POST`:`GET` 主要用于从指定资源获取数据,参数附在 URL 查询字符串之后且响应可能被缓存;`POST` 用于向指定资源提交待处理数据(也可返回结果),数据放在请求体中传输且默认不会被浏览器缓存。关于两种方法更完整的协议层差异(如幂等性、缓存控制与载荷大小限制),可结合专门的 HTTP 方法对比文档进一步延伸学习。

jQuery $.get() 方法语法与实测

`$.get()` 通过 HTTP GET 向服务器请求数据,常见简写为 `$.get(URL, callback)`,完整签名为 `$.get(URL [, data] [, callback] [, dataType])`:必需参数 `URL` 为目标地址;可选 `data` 为附加到查询字符串的文本或键值对;可选 `callback` 在请求成功后触发;可选 `dataType` 指定预期返回类型(默认根据响应头智能推断,支持 `xml`、`json`、`script`、`html` 或 `text`)。

在典型 GET 示例中,客户端向服务端脚本(如仅执行 `echo` 输出文本的 `demo_test.php`)发起请求,并在回调函数 `(data, status)` 中接收响应正文与请求状态。本站本地 `127.0.0.1` 回环服务与离线 Chromium 实测:点击按钮调用 `$.get('/demo_test.php', cb)` 后回调收到 `data='这是个从服务端接口读取的数据。'`、`status='success'`;进一步调用 `$.get('/demo_test_json', {lang: 'zh'}, cb, 'json')` 时,服务端确切收到带查询串 `?lang=zh` 且请求体为空的 `GET` 请求,客户端自动解析得到 JavaScript 对象 `{course: 'jQuery', method: 'GET', lang: 'zh'}`。

jQuery $.post() 方法语法、表单提交与转义实测

`$.post()` 通过 HTTP POST 向服务器提交数据,简写与完整签名与 `$.get()` 保持一致:`$.post(URL, callback)` 或 `$.post(URL [, data] [, callback] [, dataType])`,四个参数分别对应请求地址、待提交字符串或键值对、成功回调及预期响应类型。

向服务端提交表单字段(如 `name` 与 `url`)时,服务端脚本(对应 PHP 中的 `$_POST` 读取并结合 `htmlspecialchars()` 转义特殊字符)负责校验处理并返回结果,客户端回调函数再通过第一、第二参数读取正文与状态。本站本地回环实测提交 `{name: '蓝色天空网', url: 'https://example.org/demo?a=1&b=2'}`:服务端观测到请求方法为 `POST`、URL 查询串为空、`Content-Type` 为 `application/x-www-form-urlencoded; charset=UTF-8` 且表单键为 `['name', 'url']`;服务端按 `htmlspecialchars` 等价规则将 `&` 转义为 `&`,客户端回调收到 `status='success'` 及准确回显文本。

在本地 127.0.0.1 回环服务与离线 Chromium 中对比 $.get() 与 $.post() 的请求报文、JSON 解析与转义回显

含完整源码 · 220 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery Chapter 28 (ajax-get-post)."""
import html as html_mod
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import sync_playwright

INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>jQuery $.get() and $.post() Lab</title></head>
<body>
  <button id="btn-get" type="button">发送 GET 请求</button>
  <button id="btn-post" type="button">发送 POST 请求</button>
  <script>
    window.__records = [];
    (function (global) {
      function parseResponse(xhr, dataType) {
        const ct = (xhr.getResponseHeader("Content-Type") || "").toLowerCase();
        const raw = xhr.responseText;
        if (dataType === "json" || (!dataType && ct.includes("application/json"))) {
          return JSON.parse(raw);
        }
        return raw;
      }
      function send(method, url, data, callback, dataType) {
        if (typeof data === "function") {
          dataType = callback;
          callback = data;
          data = null;
        }
        const xhr = new XMLHttpRequest();
        let targetUrl = url;
        let body = null;
        if (method === "GET" && data) {
          const qs = typeof data === "string" ? data : new URLSearchParams(data).toString();
          targetUrl += (targetUrl.includes("?") ? "&" : "?") + qs;
        }
        xhr.open(method, targetUrl, true);
        if (method === "POST" && data) {
          xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
          body = typeof data === "string" ? data : new URLSearchParams(data).toString();
        }
        xhr.onload = function () {
          const ok = xhr.status >= 200 && xhr.status < 300;
          const status = ok ? "success" : "error";
          if (ok && callback) {
            callback(parseResponse(xhr, dataType), status, xhr);
          }
        };
        xhr.send(body);
      }
      global.$ = function (sel) {
        const el = document.querySelector(sel);
        return {
          click(fn) {
            if (el) el.addEventListener("click", fn);
            return this;
          }
        };
      };
      global.$.get = (url, data, cb, dt) => send("GET", url, data, cb, dt);
      global.$.post = (url, data, cb, dt) => send("POST", url, data, cb, dt);
    })(window);

    $("#btn-get").click(function () {
      $.get("/demo_test.php", function (data, status) {
        window.__getResult = { data, status };
      });
    });

    $("#btn-post").click(function () {
      $.post(
        "/demo_test_post.php",
        { name: "蓝色天空网", url: "https://example.org/demo?a=1&b=2" },
        function (data, status) {
          window.__postResult = { data, status };
        }
      );
    });
  </script>
</body>
</html>
"""


def start_server(state):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, format, *args):
            pass

        def _send(self, code, content_type, body, extra_headers=None):
            data = body.encode("utf-8")
            self.send_response(code)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(data)))
            for k, v in (extra_headers or {}).items():
                self.send_header(k, v)
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):
            parts = urlsplit(self.path)
            qs = {k: v[0] for k, v in parse_qs(parts.query).items()}
            state["log"].append({"method": "GET", "path": parts.path, "query": qs, "body": ""})
            if parts.path == "/":
                self._send(200, "text/html; charset=utf-8", INDEX_HTML)
            elif parts.path == "/demo_test.php":
                self._send(200, "text/plain; charset=utf-8", "这是个从服务端接口读取的数据。", {"Cache-Control": "max-age=60"})
            elif parts.path == "/demo_test_json":
                payload = {"course": "jQuery", "method": "GET", "lang": qs.get("lang", "")}
                self._send(200, "application/json; charset=utf-8", json.dumps(payload, ensure_ascii=False))
            else:
                self._send(404, "text/plain; charset=utf-8", "Not Found")

        def do_POST(self):
            parts = urlsplit(self.path)
            length = int(self.headers.get("Content-Length", "0"))
            raw = self.rfile.read(length).decode("utf-8")
            params = {k: v[0] for k, v in parse_qs(raw).items()}
            state["log"].append({
                "method": "POST",
                "path": parts.path,
                "query": {},
                "content_type": self.headers.get("Content-Type", ""),
                "body_keys": sorted(params.keys()),
            })
            if parts.path == "/demo_test_post.php":
                name = html_mod.escape(params.get("name", ""), quote=True)
                url = html_mod.escape(params.get("url", ""), quote=True)
                self._send(200, "text/plain; charset=utf-8", f"网站名: {name}\nURL 地址: {url}", {"Cache-Control": "no-store"})
            else:
                self._send(404, "text/plain; charset=utf-8", "Not Found")

    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    return server


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    state = {"log": []}
    server = start_server(state)
    base_url = f"http://127.0.0.1:{server.server_port}"
    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page(viewport={"width": 1000, "height": 700})
                page.goto(base_url + "/")

                page.click("#btn-get")
                page.wait_for_function("() => Boolean(window.__getResult)")
                c1 = page.evaluate("() => window.__getResult")
                exp1 = {"data": "这是个从服务端接口读取的数据。", "status": "success"}
                cases.append({"name": "get_basic_text_and_status", "passed": c1 == exp1, "expected": exp1, "actual": c1})

                page.evaluate("""() => {
                    $.get("/demo_test_json", { lang: "zh" }, function (data, status) {
                        window.__jsonResult = { data, status, isObject: typeof data === "object" };
                    }, "json");
                }""")
                page.wait_for_function("() => Boolean(window.__jsonResult)")
                c2 = page.evaluate("() => window.__jsonResult")
                exp2 = {
                    "data": {"course": "jQuery", "method": "GET", "lang": "zh"},
                    "status": "success",
                    "isObject": True,
                }
                cases.append({"name": "get_with_query_params_and_json_datatype", "passed": c2 == exp2, "expected": exp2, "actual": c2})

                page.click("#btn-post")
                page.wait_for_function("() => Boolean(window.__postResult)")
                c3 = page.evaluate("() => window.__postResult")
                exp3 = {
                    "data": "网站名: 蓝色天空网\nURL 地址: https://example.org/demo?a=1&amp;b=2",
                    "status": "success",
                }
                cases.append({"name": "post_form_data_and_escaping", "passed": c3 == exp3, "expected": exp3, "actual": c3})

                get_entry = next(x for x in state["log"] if x["path"] == "/demo_test_json")
                post_entry = next(x for x in state["log"] if x["path"] == "/demo_test_post.php")
                c4 = {
                    "get_method": get_entry["method"],
                    "get_query": get_entry["query"],
                    "get_body_empty": get_entry["body"] == "",
                    "post_method": post_entry["method"],
                    "post_query_empty": post_entry["query"] == {},
                    "post_body_keys": post_entry["body_keys"],
                    "post_content_type": post_entry["content_type"],
                }
                exp4 = {
                    "get_method": "GET",
                    "get_query": {"lang": "zh"},
                    "get_body_empty": True,
                    "post_method": "POST",
                    "post_query_empty": True,
                    "post_body_keys": ["name", "url"],
                    "post_content_type": "application/x-www-form-urlencoded; charset=UTF-8",
                }
                cases.append({"name": "get_vs_post_request_semantics", "passed": c4 == exp4, "expected": exp4, "actual": c4})
            finally:
                browser.close()
    finally:
        server.shutdown()
        server.server_close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 $.get() 返回文本与解析后的 JSON 对象、$.post() 以表单编码请求体提交且服务端转义 & 为 &amp;,并逐项对比 GET/POST 的查询串、请求体与 Content-Type。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a875.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a875.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

$.get() 将 data 序列化为 URL 查询字符串发送(请求体为空),$.post() 将 data 以 application/x-www-form-urlencoded 格式放入请求体发送;服务端对用户输入做 HTML 实体转义(如 PHP 的 htmlspecialchars)可防止特殊字符破坏输出结构或引发 XSS 注入。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习