Asp.net通过Jquery操作WebService进行Ajax读写
一说到开始,我们当然需要项目。
首先,创建一个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();
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();
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>);
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 = , 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();
});
});
Asp.net通过Jquery操作WebService进行Ajax读写的更多相关文章
- ASP.net jQuery调用webservice返回json数据的一些问题
之前寒假时,试着使用jQuery写了几个异步请求demo, 但是那样是使用的webform普通页面,一般应该是用 webservice 居多. 最近写后台管理时,想用异步来实现一些信息的展示和修改, ...
- jquery操作ajax返回的页面元素
这两天工作不忙,正好从朋友那里拿到一个某个应用的开发文档,相关数据放在了mongodb里,自己电脑可以本地开启服务器然后通过给的借口来获取数据.由于这是一个比较大比较全的一个完整项目,也没有那么多经历 ...
- jQuery框架-2.jQuery操作DOM节点与jQuery.ajax方法
一.jQuery操作DOM 内部插入操作: append(content|fn):向每个匹配的元素内部追加内容. prepend(content):向每个匹配的元素内部前置内容. 外部插入操作: af ...
- 如何构建ASP.NET MVC4&JQuery&AJax&JSon示例
背景: 博客中将构建一个小示例,用于演示在ASP.NET MVC4项目中,如何使用JQuery Ajax. 步骤: 1,添加控制器(HomeController)和动作方法(Index),并为Inde ...
- json数据的jquery操作和asp.net后台操作
jquery操作 json对象创建 var item0={"a":"val1","b":"val2"}; json对象字 ...
- jQuery入门(2)使用jQuery操作元素的属性与样式
jQuery入门(1)jQuery中万能的选择器 jQuery入门(2)使用jQuery操作元素的属性与样式 jQuery入门(3)事件与事件对象 jQuery入门(4)jQuery中的Ajax()应 ...
- jQuery调用WebService实现增删改查的实现
第一篇博客,发下我自己写的jQuery调用WebService实现增删改查的实现. 1 <!DOCTYPE html> 2 3 <html xmlns="http://ww ...
- Jquery调用Webservice传递Json数组
Jquery由于提供的$.ajax强大方法,使得其调用webservice实现异步变得简单起来,可以在页面上传递Json字符串到Webservice中,Webservice方法进行业务处理后,返回Js ...
- 通过jQuery或ScriptManager以Ajax方式访问服务
1.客户端和服务端 服务端对外提供服务时,可以通过handler或者webservice.handler比较轻便,但是难以对外公开,只有程序员自己知道它到底做了些什么工作.webservice可以将服 ...
随机推荐
- 关于 xib 的使用
前两天写百度地图的时候要添加 一个标注的泡泡view 但有些复杂所以想用xib 拖拽出一个View ,拖拽出来之后发现添加不到Controller中 ,郁闷!! 终于找到了方法: //先获取NIb ...
- 开始玩mondrian
官网:http://community.pentaho.com/projects/mondrian/ 官方编译的包:https://sourceforge.net/projects/mondrian/ ...
- redis-集群(cluster)扫盲篇(一)
什么是redis的集群 按我个人的理解,redis集群就是实现多个redis节点之间进行数据的共享. 集群有什么好处: 将数据自动split到多个节点进行存储. 当集群中的一部分节点失效或者无法进行通 ...
- 关于Tomcat启动时报The APR based Apache Tomcat Native library which allows optimal performanc e in production environments was not found on the java.library.path
错误信息如下 八月 01, 2016 10:11:15 上午 org.apache.catalina.core.AprLifecycleListener initINFO: The APR based ...
- 在类库项目中使用log4net(RollingFileAppender)记录日志
1.创建解决方案 2.创建类库项目 3.根据需要修改命名空间,修改(和/或)添加类到类库 4.引用log4net 5.类库项目根目录下创建leg4net配置文件,如D3CallTriggerPlugi ...
- TOMCAT报错:HTTP Status 404 -
构建struts2工程师,tomcat报错: HTTP Status 404 - type Status report message description The requested resour ...
- 深入PHP内核之in_array
无意中看到一段代码 1.a.php <?php $y="12"; $x = array(); for($j=0;$j<50000;$j++){ $x[]= " ...
- SQL 统计表行数和空间大小
CREATE TABLE #tablespaceinfo ( nameinfo VARCHAR() , rowsinfo BIGINT , reserved VARCHAR() , datainfo ...
- MySQL在创建相同表结构时as和like 使用的区别
1.MySQL的复制相同表结构方法: 1)create table table_name as select * from table1 where 1=2 (或者limit 0): 2) crea ...
- SQL TUNNING
In a Nested Loops Join, for example, the first accessed table is called the outer table and the seco ...