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) + "}";
}
前台代碼
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.111cn.net/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml" >
<head>
<title>無標題頁</title>
<style type="text/css教程">
.show{ display:block;}
.hide{ display:none;}
</style>
<script type="text/網頁特效" src="jquery/jquery-1.2.6.js"></script>
<script type="text/網頁特效">
//這個方法把ajax方法封裝一下,方便調用。
function myajax(){
//var obj=jsondata();
$.ajax({
type:'post',
url:'ajax.asp教程x',
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>