DIV CSS 佈局教程網

傳遞參數的標準做法:用 jQuery 物件而非字串拼接
編輯:JQuery特效代碼     

前台

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<title>無標題頁</title>
<script type="text/javascript" src="jquery/jquery-1.2.6.js"></script>
<script type="text/javascript">
// 這個方法把 ajax 方法封裝一下,方便調用。
function myajax(){
    // 用此法傳遞數據
    var arr = {
        "name": "tree",
        "id": "123"
    };

    $.get(
        "ajax.aspx",
        arr,
        callback,
        "json"
    );
}

// 回呼函式
function callback(data){
    $('#response').append(data.name + data.id);
    $('#wait').css("display", "none");
}

// onload 事件
$(function(){
    $('#confirm').click(myajax);
})

// 封裝 json 資料,為了程式碼清晰——看來這種方法不行,
// 似乎是因為陣列格式不對。
function jsonData(){
    var jsonStr = "";
    jsonStr += "\"name\":";
    jsonStr += "\"tree\"";
    jsonStr += ",";
    jsonStr += "\"id\":";
    jsonStr += "\"123\"";
    jsonStr += "}";
    return jsonStr;
}
</script>
</head>
<body>
<div id="confirm">點擊</div>
<div id="response">接收後台數據</div>
<div id="wait" class="hide">hello</div>
</body>
</html>

後台

public partial class ajax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Response.Write("hello" + Request["name"]);
        Hashtable ht = new Hashtable();
        ht.Add("name", Request.Params["name"]);
        ht.Add("id", Request.Params["id"]);
        Response.Write(CreateJsonParams(ht));
        Response.End();
    }

    private string CreateJsonParams(Hashtable items)
    {
        string returnStr = "";
        foreach (DictionaryEntry item in items)
        {
            returnStr += "\"" + item.Key.ToString() + "\":\"" + item.Value.ToString() + "\",";
        }
        return "{" + returnStr.Substring(0, returnStr.Length - 1) + "}";
    }
}

為什麼物件寫法才是標準做法

作者一開始試著用函式回傳 JSON 字串來傳參數,結果行不通(註解裡寫著「看來這種方法不行,似乎是因為陣列格式不對」)。最後改用最直觀的寫法:

var arr = {
    "name": "tree",
    "id": "123"
};

直接把物件傳給 $.get() 的第二個參數,jQuery 會自動負責序列化與 URL 編碼。這才是官方推薦的方式,原因有三:

  • 不必手動處理編碼:中文、空格、&、= 等特殊字元都不用自己 escape。
  • 不會漏加分隔符號:字串拼接最常見的 bug 就是少了一個 & 或多了一個逗號。
  • 程式碼可讀性高:一眼就看懂傳了哪些參數。

後端組 JSON 的注意事項

範例中的 CreateJsonParams() 用手動拼接的方式組出 JSON。這在 C# 里是早期常見做法,但有兩個風險:

  • 若值裡含有雙引號或反斜線,會產生無效的 JSON,前端解析就會失敗。
  • Hashtable 的走訪順序不固定,若前端依賴欄位順序會出問題。

建議改用內建的序列化機制,例如 System.Web.Script.Serialization.JavaScriptSerializer 或 Newtonsoft.Json,讓它們處理跳脫與格式問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved