這篇示範如何用 Ajax 與 JSON,為前台頁面的 <select> 繫結資料源。原理很單純:前端以 $.ajax 呼叫後端的 WebMethod,取回 JSON 陣列後動態建立 option 元素。以下是一份可直接運行的完整範例。
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="UseJason.aspx.cs" Inherits="AjaxTest.UseJason" %>
<!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 runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnGetCars").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "UseJason.aspx/GetCars",
data: "{}",
dataType: "json",
success: GetCars,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown + ":" + textStatus);
}
});
});
$("#SelectCars").change(function () {
CarSelectChange();
});
});
function GetCars(result) {
$(result.d).each(function () {
var o = document.createElement("option");
o.value = this['carName'];
o.text = this['carDescription'];
$("#SelectCars")[0].options.add(o);
});
}
function CarSelectChange() {
var opts = $("#SelectCars")[0].options;
var selected = $("#SelectCars").val();
$("#txtPrice").val(GetPriceByCarName(selected));
}
function GetPriceByCarName(name) {
var price = "";
$("#SelectCars option").each(function () {
if (this.value == name) {
price = $(this).data('price');
}
});
return price;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnGetCars" value="GetCars" />
<div style="margin-top: 20px">
<p>Cars list :</p>
<select id="SelectCars" style="width: 185px;"></select>
<p>Price :</p>
<input type="text" id="txtPrice" />
</div>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web.Services;
namespace AjaxTest
{
public partial class UseJason : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<Car> GetCars()
{
List<Car> listCars = new List<Car>()
{
new Car("A1", "A1 Description", 205000),
new Car("B12", "B12 Description", 105300),
new Car("Dfe", "Dfe Description", 658982),
new Car("Yfee", "Yfee Description", 8458700),
new Car("UUdde", "UUdde Description", 6548225)
};
return listCars;
}
}
}
using System;
using System.Collections.Generic;
namespace AjaxTest
{
public class Car
{
public string carName { get; set; }
public string carDescription { get; set; }
public double carPrice { get; set; }
public Car(string name, string description, double price)
{
this.carName = name;
this.carDescription = description;
this.carPrice = price;
}
}
}
WebMethod 必須是 static,並標上 [WebMethod]。ASP.NET 的腳本服務機制透過這個屬性辨識可呼叫端點,缺少它就會得到 500 或找不到方法的錯誤。
回應結構中的 result.d:為了避免 JSON 劫持攻擊,.NET 的腳本序列化會把結果包在一層 d 屬性裡。因此前端必須寫 result.d 而不是直接 result——這是許多人第一次使用時最常卡住的地方。
三個 header 缺一不可:type: "POST"(WebMethod 預設只接受 POST)、contentType: "application/json"(讓伺服器知道要解析 JSON)、dataType: "json"(讓 jQuery 把回應解析成物件)。少一個就會出錯。
data: "{}" 不能省略:即使沒有參數要傳,也應給一個空的 JSON 物件;完全省略 data 在部分情況下會導致請求未被正確序列化。
重複繫結前先清空:若使用者可能多次點擊按鈕,GetCars 會一再 options.add 造成重複項目。實務上應先清空:
function GetCars(result) {
var $sel = $("#SelectCars");
$sel.empty(); // 先清空,避免重複
$(result.d).each(function () {
$sel.append($('<option>', {
value : this.carName,
text : this.carDescription
}));
});
}
本篇的內容相當單純,重點在於把「WebMethod + JSON + jQuery」這條資料通道打通。下一篇可以進一步討論這個 select 的 onchange 事件——例如選了車款之後,如何再發一次非同步請求去撈對應價格,形成第二層的連動選單。