百度空间 | 百度首页 
 
查看文章
 
jQuery调用Asp.net Ajax页面中的方法
2008年06月16日 星期一 上午 01:14
原来用jQuery的ajax方式调用asp.net页面基本都是调用单个页面,由调用页面Response内容,而现在采用asp.net ajax后,我们则可以更完美的使用jQuery和asp.net结合了,代码如下:
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Path="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" ScriptMode="Release" />
</Scripts>
</asp:ScriptManager>
<div id="Result">Click here.</div>
<script language="javascript">
$(document).ready(function() {

$("#Result").click(function() {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetDate",//注意调用方式,同样方式可以调用webservice
data: {}, //在这里可以设置需要传递的参数
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// 替换返回内容
$("#Result").text(msg);
},
error: function(xhr,msg,e) { alert(msg);}
});
});
});
</script>
WebForm1.aspx(页面GetDate方法必须使用静态方法并且使用[System.Web.Services.WebMethod]属性,如调用webservice中的方法不需要静态)
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
[System.Web.Services.WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
注:带参数时
1、设置$.ajax中的data,如:data: “{'fname':'Freeze', 'lname':'Soul'}”,注意外围双引号
2、设置$.ajax中的beforeSend,如:
beforeSend: function(xhr) {
        xhr.setRequestHeader("Content-type",
                         "application/json; charset=utf-8");},
3、然后修改GetDate()方法为GetDate(String frname,String lname)

类别:asp.net ajax | 添加到搜藏 | 浏览() | 评论 (2)
最近读者:
 
网友评论:
1
2008年06月17日 星期二 上午 00:19 | 回复
.. gogogo!
 
2
2009年06月01日 星期一 上午 11:21 | 回复
就怕有问题啊,这样还是要用到.NET那个Script***这个东东,如果要这样用,何必用JQuery呢。想不明白。
介绍两个书站,楼主多读读。

http://www.4yxs.com

http://www.06du.com
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     
 
精彩相册
   
     

©2009 Baidu