處理類型
返回複雜類型
Ajax封裝器不僅能處理ServerSideAdd函數所返回的整數。它目前還支援integers、strings、double、booleans、DateTime、DataSets和DataTables,以及自訂類和數組等基本類型。其他所有類型都返回它們的ToString值。
返回的DataSets和真正的.NET DataSet差不多。假設一個伺服器端函數返回DataSet,我們可以通過下面的代碼在用戶端顯示其中的內容:
<script language="JavaScript">
//Asynchronous call to the mythical "GetDataSet" server-side function
function getDataSet(){
AjaxFunctions.GetDataSet(GetDataSet_callback);
}
function GetDataSet_callback(response){
var ds = response.value;
if(ds != null && typeof(ds) == "object" && ds.Tables != null){
var s = new Array();
s[s.length] = "<table border=1>";
for(var i=0; i<ds.Tables[0].Rows.length; i++){
s[s.length] = "<tr>";
s[s.length] = "<td>" + ds.Tables[0].Rows[i].FirstName + "</td>";
s[s.length] = "<td>" + ds.Tables[0].Rows[i].Birthday + "</td>";
s[s.length] = "</tr>";
}
s[s.length] = "</table>";
tableDisplay.innerHTML = s.join("");
}
else {
alert("Error. [3001] " + response.request.responseText);
}
}
</script>
Ajax還可以返回自訂類,唯一的要求是必須用Serializable屬性標記。假設有如下的類:
[Serializable()]
public class User{
private int _userId;
private string _firstName;
private string _lastName;
public int userId{
get { return _userId; }
}
public string FirstName{
get { return _firstName; }
}
public string LastName{
get { return _lastName; }
}
public User(int _userId, string _firstName, string _lastName){
this._userId = _userId;
this._firstName = _firstName;
this._lastName = _lastName;
}
public User(){}
[AjaxMethod()]
public static User GetUser(int userId){
//Replace this with a DB hit or something
return new User(userId,"Michael", "Schwarz");
}
}
我們可以通過調用RegisterTypeForAjax註冊GetUser代理:
private void Page_Load(object sender, EventArgs e){
Utility.RegisterTypeForAjax(typeof(User));
}
這樣就可以在用戶端非同步呼叫GetUser:
<script language="javascript">
function getUser(userId){
User.GetUser(GetUser_callback);
}
function GetUser_callback(response){
if (response != null && response.value != null){
var user = response.value;
if (typeof(user) == "object"){
alert(user.FirstName + " " + user.LastName);
}
}
}
getUser(1);
</script>
響應中返回的值實際上是一個對象,公開了和伺服器端對象相同的屬性(FirstName、LastName和UserId)。
http://www.shpan.com/Detail.asp?ID=398