DIV CSS 佈局教程網

$.ajax 傳遞 JSON 資料的前後端完整實作
編輯: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>
<style type="text/css">
.show{ display:block;}
.hide{ display:none;}
</style>
<script type="text/javascript" src="jquery/jquery-1.2.6.js"></script>
<script type="text/javascript">

// 這個方法把 ajax 方法封裝一下,方便調用。
function myajax(){
    $.ajax({
        type:'post',
        url:'ajax.aspx',
        data: jsonData(),      // 可以直接放一個函式名稱,由它回傳資料
        dataType:'json',
        beforeSend: beforecall,
        success: callback
    });
}

// 封裝 json 資料,為了程式碼清晰
function jsonData(){
    var jsonStr = "({";
    jsonStr += "\"name\":";
    jsonStr += "\"tree\"";
    jsonStr += ",";
    jsonStr += "\"id\":";
    jsonStr += "\"123\"";
    jsonStr += "})";
    return eval(jsonStr);       // 關鍵在於轉換
}

// 呼叫前的處理
function beforecall(){
    $('#wait').addClass("show").append('調出中...');
}

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

// onload 事件
$(function(){
    $('#confirm').click(myajax);
})
</script>
</head>
<body>
<div id="confirm">點擊</div>
<div id="response">接收後台數據</div>
<div id="wait" class="hide">hello</div>
</body>
</html>

後台(ASP.NET C#)

protected void Page_Load(object sender, EventArgs e)
{
    Hashtable ht = new Hashtable();
    string name  = Request.Params["name"].ToString();
    string birth = Request.Params["birthday"].ToString();

    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(birth))
    {
        // Response.ContentType = "Application/json";
        ht.Add("info", "成功了");
        ht.Add("sta", "狀態");
        ht.Add("name", name);
        ht.Add("birth", birth);
        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) + "}";
}

幾個值得注意的細節

  • data: jsonData() 直接傳函式呼叫:把資料組裝抽到獨立函式,ajax 設定區塊看起來乾淨很多。
  • 後端務必設定 ContentType:程式碼中 Response.ContentType = "Application/json"; 被註解掉了。若前端指定 dataType:'json' 而後端沒有回傳正確的 Content-Type,很可能抓不到資料。正式環境請把這行取消註解。
  • 用 Hashtable 組 JSON 而非字串拼接:這比手動拼字串安全,但注意 Hashtable 的走訪順序不固定。若前端依賴欄位順序,請改用有順序性的集合。
  • eval() 不是好習慣:範例用 eval() 把字串轉為物件。這是早期常見寫法,但 eval 會執行任意程式碼,存在資安風險。請直接寫物件字面值 {name:"tree", id:"123"},或使用 JSON.parse()。
  • Response.End():確保後端輸出後立即停止,不會再寫入頁面其他內容污染 JSON。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved