以aspx網頁 配合WebService 透過Json傳遞來達到ajax效果
首先網頁上配置
<asp:Image runat="server" Height="66px"
ImageUrl="~/image/Search.png" Width="72px" ></asp:Image>
<asp:Panel ID="Panel1" runat="server" class="panel"></asp:Panel>
js部分:
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
$('image').css("cursor", "pointer");
$('image').click(function () {
var list = ["A", "B"]; //陣列
var JsObj = { p_list: list };
var JsonText = JSON.stringify(JsObj); //轉Json格式,此方法需要加入參考 json2.js
$.ajax({
type: 'POST',
url: 'WebService.asmx/GetJsonBySend',
data: JsonText,
contentType: "application/json; charset=utf-8", //設定傳回server格式
dataType: 'json', //設定從Server接收的格式
success: function (msg) {
var jsonData = eval("(" + msg.d + ")");
var gid =
"<table cellspacing='0' cellpadding='3 border='1' >"+
"<tr><th>ID</th><th>SN</th><th>Size</th></tr>";
$.each(jsonData, function (rec) {
gid += "<tr>";
gid += "<td>" + this.id+ "</td><td>" + this.sn+ "</td><td>" + this.size+ "</td>";
gid += "</tr>";
});
gid += "</table>";
$(".panel").html(gid);
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.statusText);
// alert(xhr.responseText);
//上面兩行是開發期間,可以觀察錯誤訊息用,建議ajax正常後,可以註解掉
$(".panel").html("<span>" + xhr.responseText + "</span>");
}
}); //** ajax End **//
}); //** click End **//
}); //** ready End **//
</script>
C# Entity物件:
建立與前端相符的屬性之物件
public class CEn
{
private string _id;
public string id
{
get { return _id; }
set { _id = value; }
}
private string _sn;
public string sn
{
get { return _sn; }
set { _sn = value; }
}
private string _size;
public string size
{
get { return _size; }
set { _size = value; }
}
}
C#:WebService
新增一個WebService
記得
// 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
[System.Web.Script.Services.ScriptService] //這行要取消註解
[WebMethod]
public string GetJsonBySend(List <string > p_list ) {
//底下將物件Boxing,也可與資料庫對應,以迴圈產生
ArrayList list = new ArrayList();
CEn en1 = new CEn();
en1.id = "A1";
en1.size = "100";
en1.sn = "Ray";
CEn en2 = new CEn();
en2.id = "A2";
en2.size = "500";
en2.sn = "BigOne";
list.Add(en1);
list.Add(en2);
return GetJsonData(list);
}
private string GetJsonData(IList p_list)
{
JavaScriptSerializer JS = new JavaScriptSerializer();
//Serialize將集合物件,轉換成Json格式
return JS.Serialize(p_list);
}
配置完成後,按下image,就可以看到查詢到的結果
留言列表