萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery AJAX 調用新浪短網址 API 完整實現指南

短網址服務在社交分享、字符受限場景極具價值。本文詳細介紹如何使用 jQuery AJAX 跨域調用新浪微博短網址 API,包含 JSONP 跨域處理、參數構建、錯誤處理及完整可運行示例。

API 基礎信息

  • 接口地址:`https://api.weibo.com/2/short_url/shorten.json`
  • 請求方式:GET
  • 必需參數:`source` (App Key)、`url_long` (長網址)
  • 響應格式:JSONP(解決跨域)

完整前端實現

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>新浪短網址生成器</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <style>
        .container { max-width: 600px; margin: 50px auto; padding: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"] { width: 100%; padding: 8px; box-sizing: border-box; }
        button { padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:disabled { background: #95a5a6; cursor: not-allowed; }
        #result { margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 4px; display: none; }
        .error { color: #e74c3c; }
    </style>
</head>
<body>
    <div class="container">
        <h2>新浪短網址生成</h2>

        <div class="form-group">
            <label>長網址:</label>
            <input type="text" id="longUrl" placeholder="請輸入完整長網址" value="https://www.example.com/very/long/url/with/parameters">
        </div>

        <div class="form-group">
            <label>App Key(申請地址):</label>
            <input type="text" id="appKey" placeholder="輸入您的 App Key">
        </div>

        <button id="generateBtn">生成短網址</button>

        <div id="result">
            <h4>結果:</h4>
            <p>短網址:<a id="shortUrl" href="#" target="_blank"></a></p>
            <p>調用地址:<code id="apiUrl"></code></p>
        </div>

        <p class="error" id="errorMsg" style="display:none;"></p>
    </div>

    <script>
    $(function() {
        $("#generateBtn").on("click", function() {
            var longUrl = $("#longUrl").val().trim();
            var appKey = $("#appKey").val().trim();
            var $btn = $(this);
            var $result = $("#result");
            var $error = $("#errorMsg");

            // 驗證
            if (!longUrl) {
                showError("請輸入長網址");
                return;
            }
            if (!appKey) {
                showError("請輸入 App Key");
                return;
            }
            if (!/^https?:\/\//.test(longUrl)) {
                showError("請輸入有效的 HTTP/HTTPS 網址");
                return;
            }

            // 構建 API 請求
            var apiUrl = "https://api.weibo.com/2/short_url/shorten.json";
            var params = {
                source: appKey,
                url_long: longUrl
            };

            $btn.prop("disabled", true).text("生成中...");
            $error.hide();
            $result.hide();

            // JSONP 跨域請求
            $.ajax({
                url: apiUrl,
                type: "GET",
                data: params,
                dataType: "jsonp", // 關鍵:使用 JSONP 解決跨域
                jsonp: "callback", // 回調參數名(新浪 API 要求)
                timeout: 10000,
                success: function(response) {
                    if (response.data && response.data.urls && response.data.urls.length > 0) {
                        var short = response.data.urls[0].url_short;
                        $("#shortUrl").attr("href", short).text(short);
                        $("#apiUrl").text(apiUrl + "?" + $.param(params));
                        $result.show();
                    } else {
                        showError("API 返回數據格式異常: " + JSON.stringify(response));
                    }
                },
                error: function(xhr, status, error) {
                    var msg = "請求失敗";
                    if (status === "timeout") msg = "請求超時,請檢查網絡";
                    else if (status === "parsererror") msg = "JSONP 解析失敗,請檢查 App Key";
                    showError(msg + ": " + error);
                },
                complete: function() {
                    $btn.prop("disabled", false).text("生成短網址");
                }
            });
        });

        function showError(msg) {
            $("#errorMsg").text(msg).show();
        }
    });
    </script>
</body>
</html>

關鍵技術點解析

1. JSONP 跨域原理

瀏覽器同源策略限制 AJAX 跨域,但 `

copyright © 萬盛學電腦網 all rights reserved