您的位置:首页 > Web前端 > JQuery

Asp.net通过Jquery操作WebService进行Ajax读写

2013-09-10 22:15 621 查看
一说到开始,我们当然需要项目。

首先,创建一个Asp.net Web 应用,然后新增一个名称为“Web 服务”的文件,也就是后缀名为".asmx"的文件,然后需要进行配置一下,在Web.Config中加入如下配置节点:

在HttpHandlers节点中,需要注册:

<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>


然后需要在System.Web下注册WebServices节点:

<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>


配置完毕后,下面开始进行具体的讲解。
1.利用Get方式进行数据读写操作

首先,前台,我们代码如下:

$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
url: "Ajax/WebService1.asmx/HelloWorld",
type: "get",
data: "name=John&location=Boston",
success: function (result) {
$("#test").html(result.text);
},
error: function (data) {
alert(data.value);
}
});
});
});


后台,我们的代码如下:

using System.Web.Services;
using System.Threading;

namespace Nxt.Web.Ajax
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

[WebMethod]
public string HelloWorld()
{
Thread.Sleep(3000);
return this.Context.Request.QueryString["name"];
}
}
}


得到的结果如我们预料,服务器端返回了“John”。

2.利用Post方式进行数据读写操作。

首先是前端代码:

$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
url: "Ajax/WebService2.asmx/HelloWorld",
type: "post",
contentType: "application/json",  //from backend
dataType: "json",  // send to backend
data: '{"name":"test"}',
success: function (result) {
$("#test").html(result.d);
},
error: function (data) {
//alert(data.value);
}
});
});
});


然后是后端的处理过程,在前端代码中,我们可以看到,我们通过contentType: "application/json",表明后台传送到前台的是JSON格式的数据。 而通过dataType: "json",则表明我们往后端传送的也是json类型的数据。

using System.Web.Services;
using System.Threading;

namespace Nxt.Web.Ajax
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(string name)
{
Thread.Sleep(3000);
return name;
}
}
}


这样,我们通过Post方式得到了预期的结果。
这里我需要特别说明的是,当用json数据当做参数通过Post方式传入后台的时候,后台的参数名称可以与前台保持一致。

那么我们后台取值的时候,直接把参数拿过来用就行了。在例子里,我的json数据为:{"name":"test"},那么在后台,我需要获取的值,就保存在了参数 string name中了。

直接拿过来用就行了。

3.直接操作后台返回的List对象

前台代码如下:

$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
url: "Ajax/WebService2.asmx/GetList",
type: "post",
contentType: "application/json",  //from backend
dataType: "json",  // send to backend
data: '{"i":"10"}',
success: function (result) {
$(result.d).each(function (value) {
$("#test").append(this.toString()+" ");
});
},
error: function (data) {
//alert(data.value);
}
});
});
});


后台代码如下:

[WebMethod]
public List<int> GetList(int i)
{
List<int> list = new List<int>();
do{
list.Add(i);
i--;
}while(i>0);
return list;
}


最后,屏幕上打印出了我们需要的数据: 10 9 8 7 6 5 4 3 2 1。

4.直接操作后台返回类对象

前台:

$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
url: "Ajax/WebService2.asmx/GetModel",
type: "post",
contentType: "application/json",  //from backend
dataType: "json",  // send to backend
data: '{}',
success: function (result) {
$(result.d).each(function (value) {
debugger;
$("#test").append(this["UserID"].toString() + " " + this["UserName"].toString() + " " + this["UserAddr"].toString());
});
},
error: function (data) {
debugger;
//alert(data.value);
}
});
});
});


后台代码:

[WebMethod]
public Common.TestModel GetModel()
{
return new Common.TestModel { UserID = 1, UserName = "nxt", UserAddr = "beijing" };
}


5.直接操作返回的dataset数据集

前端代码:

$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
url: "Ajax/WebService2.asmx/GetDataSet",
type: "post",
dataType: "xml",  // send to backend
data: '{}',
success: function (result) {
try {
$(result).find("Table1").each(function () {
$("#test").append($(this).find("ID").text() + " " + $(this).find("Value").text());
});
}
catch (e) {
alert(e);
return;
}
},
error: function (data) {
//alert(data.value);
}
});
});
});


后端代码:

[WebMethod]
public DataSet GetDataSet()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Value", Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["ID"] = "scy";
dr["Value"] = "河南理工大学";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "scy1";
dr["Value"] = "河南理工大学1";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
return ds;
}


得到的结果是:scy 河南理工大学scy1 河南理工大学1

符合预期。

最后加一个loading效果的特效,以便备忘:

<style type="text/css">
#loading
{
position:absolute;
top:50%;
left:50%;
}
</style>


$(document).ready(function () {
$('#loading').ajaxStart(function () {
$(this).html("<img src='Images/loading.gif'>").show();
}).ajaxStop(function () {
$(this).hide();
});
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐