加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Ajax]ajax学习与理解

发布时间:2020-12-16 00:46:41 所属栏目:百科 来源:网络整理
导读:1.新建demo.aspx页面。 2.首先在该页面的后台文件demos.aspx.cs中添加引用。 using System.Web.Services; 3.无参数的方法调用. 大家注意了,这个版本不能低于.net framework 2.0。2.0已下不支持的。 后台代码: [WebMethod] public static string SayHello()

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代码:

复制代码

$(function() {     
$(").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>

运行结果图:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读