自己雖然以前也用ajax但總感覺那裡覺得不對,以前ajax都是請求aspx頁面,那頁面多的數不清,自己也覺得很亂。
自己最近在工作中,也覺得同事用的jquery+ashx用起來相當的簡潔方便。幫在這裡做了一個小的demo來
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxGet.aspx.cs" Inherits="AjaxGet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
<script type="text/javascript" src="misc/js/jquery-1.2.6.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
function GetCategoryData(type)
{
alert("test start");
$.ajax({
type:'GET',
url:'AjaxService/Handler.ashx',
dataType: 'text',
data:'type='+type,
success:function(msg)
{
alert(msg);
$("#category").html(msg);
},
error: function(data){
alert(data);
}
})
}
</script>
<form id="form1" runat="server">
<div>
<input type="radio" value="1" name="wangtao" onclick='GetCategoryData(this.value)' />
<input type="radio" value="2" name="wangtao" onclick='GetCategoryData(this.value)' />
<select id="category" >
</select>
</div>
</form>
</body>
</html>
前台頁後很簡單了,就是兩個radio和一個select。要把選中的radio的值放在select中去。
後台ashx代碼
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Text;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
StringBuilder strBul = new StringBuilder();
strBul.Append("<option value='wangtao'>");
strBul.Append( context.Request.Params["type"].ToString());
strBul.Append("</option>");
context.Response.ContentType = "text/html";
context.Response.Write(strBul.ToString());
}
public bool IsReusable {
get {
return false;
}
}
}
雖然很簡單,但可以供大家舉一反三。