微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Ajax]ajax学习与理解

1.新建demo.aspx页面
2.首先在该页面后台文件demos.aspx.cs中添加引用。

using System.Web.Services;
3.无参数的方法调用.
大家注意了,这个版本不能低于.net framework 2.0。2.0已下不支持的。
后台代码
[WebMethod]     
public static string SayHello()
{
return "Hello Ajax!";
}
JS代码
$(function() {     
$(#btnOK").click(function() {
$.ajax({
//要用post方式
type: Post",
方法所在页面方法
url: Demo.aspx/SayHello contentType: application/json; charset=utf-8 dataType: json success: function(data) {
返回的数据用data.d获取内容
alert(data.d);
},
error: function(err) {
alert(err);
}
});

禁用按钮的提交
return false;
});
});
页面代码
    <form id=form1" runat=server">
<div>
<asp:Button ID="btnOK" Text=验证用户" />
</div>
</form>
运行效果如下: 

3.有参数方法调用
后台代码
string GetStr(string str,string str2)
{
return str + str2;
}
JS代码
").click(function() {
$.ajax({
type: url: demo.aspx/GetStr方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字
data: {'str':'我是','str2':'XXX'}
alert(data.d);
},255); line-height:1.5!important">false
;
});
});
运行效果如下:

4.返回数组方法
后台代码:

[WebMethod]     
static List<string> GetArray()
{
List<string> li = new List<string>();

for (int i = 0; i < 10; i++)
li.Add(i + "");

return li;
}

JS代码

demo.aspx/GetArray插入前先清空ul
$(#list").html("");

递归获取数据
$(data.d).each(function() {
插入结果到li里面
$(").append(<li>" + this + </li>");
});

alert(data.d);
},255); line-height:1.5!important">false;
});
});
页面代码

<form id= "form1" runat= "server" >
<div>
<asp:Button ID= "btnOK" Text= "验证用户" />
</div>
<ul id= "list" >
</ul>
</form>

运行结果图:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐