前台
複製代碼 代碼如下:
<!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>
<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(){
//var obj=jsonData();
$.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('調出中...');
//alert('');//測試是否調用
}
//回呼函數
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>
後台
複製代碼 代碼如下:
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";
//Response.Write(CreareJson("this is ok!", 1, name, birth));
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) + "}";
}