function testGet3() {
$.ajax({
type: 'get',
url: 'NormalPage.aspx?action=getTime',
async: true,
success: function (result) {
setContainer(result);
},
error: function () {
setContainer('ERROR!');
}
});
}
看一下执行效果,这是Chrome的监视结果
using System;using System.Collections.Generic;using System.Linq;using System.Web;using Newtonsoft.Json;namespace Web
{ ///
/// Summary description for Handler ///
public class Handler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
Student stu = new Student(); int Id = Convert.ToInt32(context.Request.Form["ID"]); if (Id == 1)
{
stu.Name = "Byron";
} else
{
stu.Name = "Frank";
} string stuJsOnString= JsonConvert.SerializeObject(stu);
context.Response.Write(stuJsonString);
} public bool IsReusable
{ get
{ return false;
}
}
}
}
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Web
{ public class Student
{ public int ID { get; set; } public string Name { get; set; }
}
}
看看页面如何处理
function testPost() {
$.ajax({
type: 'post',
url: 'Handler.ashx',
async: true,
data: { ID: '1' },
success: function (result) {
setContainer(result); var stu =eval ('('+result+')');
setContainer(stu.ID);
setContainer(stu.Name);
},
error: function () {
setContainer('ERROR!');
}
});
}
结果是这个样子的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Web
{ ///
/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(COnformsTo= WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public Student GetStudent(int ID)
{ if (ID == 1)
{ return new Student() { ID = 1, Name = "Byron" };
} else
{ return new Student() { ID = 2, Name = "Frank" };
}
}
[WebMethod]
public string GetDateTime(bool isLong)
{
if (isLong)
{
return DateTime.Now.ToLongDateString();
}
else
{
return DateTime.Now.ToShortDateString();
}
}
}
}