Jquery调用Webservice传递Json数组
Jquery由于提供的$.ajax强大方法,使得其调用webservice实现异步变得简单起来,可以在页面上传递Json字符串到Webservice中,Webservice方法进行业务处理后,返回Json对象给页面,让页面去展现。
这一切都非常的简单,今天要学习的并非这些。我们在实际处理业务过程中,会发现往往页面要传递给webservice 的并非一个或多个字符串,有时候需要传递的是一个组合数据,如这样的一组数据:
{'Employee': [{'name':'John','sex':'man','age':'25'},{'name':'Tom','sex':'man','age':'21'}]}
客户端将这样的Json字符串作为$.ajax方法的data参数是没有问题的,然而,服务端的webservice该如何去写接收参数却成为了一个问题。在百度、谷歌了一番后,只发现提问的却没有回答的。索性还是自己去研究吧,发现其实Employee对象首先是一个数组,其次数组的每一项都是一个Dictionary<string,string>字典类型。于是我尝试在服务端使用Dictionary<string,string>[] Employee来接收客户端传递的参数,一切如我所料,成功!
客户端代码如下:
代码 //JQuery 调用webService导入数据
function LoadData() {
var studentData = CollectionData();
$.ajax({
url: "ImportDataService.asmx/ImportStu",
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: "{'students':[{'name':'KoBe ','sex':'boy','age':'20'},{'name':'Mary','sex':'girl','age':'19'}]}",
success: function(result) {
alert(result.d);
},
error: function(e) {
alert(e.responseText);
}
});
}
服务端代码如下:
代码 /// <summary>
///
/// </summary>
/// <param name="students"></param>
/// <returns></returns>
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string ImportStu(Dictionary<string,string> []students)
{
if (students.Length == )
{
return "没有任何数据!";
}
else
{
try
{
foreach (Dictionary<string, string> stu in students)
{
//构造一个新的Student对象。
Student student = new Student(); //为新构造的Student对象属性赋值。
foreach (string key in stu.Keys)
{
switch (key)
{
case "name":
student.Name = stu[key];
break;
case "sex":
student.Sex = stu[key];
break;
case "age":
int age;
if (Int32.TryParse(stu[key], out age))
{
student.Age = age;
}
else
{
student.Age = ;
}
break;
default:
break;
}
}
}
return "导入学生成功!";
}
catch
{
throw new Exception("导入学生失败!");
}
}
}
需要注意的是,服务端参数名需要和客户端Json数组的key值相同,如上代码中,参数名都为students。
以上是转自:http://www.cnblogs.com/RascallySnake/archive/2010/04/08/1707521.html
服务端代码如下:
using System.Web.Script.Services;
using System.Web.Services;
using WebWeatherWarning.Action; namespace WebWeatherWarning
{
/// <summary>
/// WeatherService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[ScriptService]
public class WeatherService : WebService
{ [WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetWeather()
{
const string sql = "SELECT * FROM DUAL";
var result=WeatherTask.GetInstance().GetWeather(sql);
return result != null ? ParseTags(result) : null;
}
public static string ParseTags(string htmlStr)
{
return System.Text.RegularExpressions.Regex.Replace(htmlStr, "<[^>]*>", "");
}
}
客户端代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="Lib/jquery-1.8.2.min.js"></script>
<script>
$(function() {
$("#btnQuery").click(function() {
$.ajax({
type: "GET", //访问WebService使用Post方式请求
contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
url: "/WeatherService.asmx/GetWeather", //调用WebService
data: "{}", //Email参数
dataType: 'json',
beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
error: function (x, e) { },
success: function (response) { //回调函数,result,返回值
debugger; var json = eval('(' + response.d + ')');
if (json && json.length > ) {
$("#content").html(json[].PCONTENT);
} else {
alert("没有数据!!!");
}
}
}); }); }) </script>
</head> <body>
<input id="btnQuery" type="button" value="button"/>
<div>
<p id="content"></p>
</div>
</body>
</html>
配置文件代码如下:
web.config里需要配置2个地方
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
在<system.web></system.web>之间加入
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
<httpRuntime/>
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
<pages controlRenderingCompatibilityVersion="4.0"/>
<compilation debug="true"/>
</system.web>
Jquery调用Webservice传递Json数组的更多相关文章
- jQuery调用WebService返回JSON数据
相信大家都比较了解JSON格式的数据对于ajax的方便,不了解的可以从网上找一下这方面的资料来看一下,这里就不多说了,不清楚的可以在网上查一下,这里只说一下因为参数设置不当引起的取不到返回值的问题. ...
- ASP.net jQuery调用webservice返回json数据的一些问题
之前寒假时,试着使用jQuery写了几个异步请求demo, 但是那样是使用的webform普通页面,一般应该是用 webservice 居多. 最近写后台管理时,想用异步来实现一些信息的展示和修改, ...
- silverlight调用WebService传递json接收绑定数据
1.接收数据: WebService通过接口接收数据.类型为object 2.类型转换: 通过json转换方法将object转换为json格式数据 3.调用WebService方法: silverli ...
- jQuery调用WebService实现增删改查的实现
第一篇博客,发下我自己写的jQuery调用WebService实现增删改查的实现. 1 <!DOCTYPE html> 2 3 <html xmlns="http://ww ...
- Jquery Ajax方法传递json到action
ajax向后台传入json需要设置option,如下 contentType:'application/json' data:Json.Stringify(jsObj) 后台处理复杂json对象(不知 ...
- jQuery调用WebService ( 同源调用)
转自原文 jQuery调用WebService 1.编写4种WebService方法 [WebService(Namespace = "http://tempuri.org/&quo ...
- Jquery 处理返回的 Json 数组
Jquery 处理返回的 Json 数组 <script> for (var i = 0; i < photos.length; ++ i) { console.log(photos ...
- Asp.Net_Ajax调用WebService返回Json前台获取循环解析
利用JQuery的$.ajax()可以很方便的调用 asp.net的后台方法.但往往从后台返回的json字符串不能够正确解析,究其原因,是因为没有对返回的json数据做进一步的加工.其实,这里只需 要 ...
- Js前端传递json数组至服务器端并解析的实现。
最近做的一个小项目中需要将json数组数据传递到服务器端进行保存,现分享一下解决思路. 环境:EasyUi+Mvc 4.0 如下: 在上述截图中的红色圈起来的部分,需要在点击保存后通过一次ajax请求 ...
随机推荐
- 第十章 Vim程序编辑器学习
1.Vim是进阶版的vi,vim不但可以用不同颜色显示文字内容,还能进行诸如shell script,C program等程序编辑功能. 区别:vi是老师的字处理器,不过功能已经很齐全,但还是有可以进 ...
- 老师你好。使用cordova生成的hellowold 的安卓5.0版本太高。怎么才可以生成4.4的呢?
你好 在你的应用目录,有个config.xml文件,课程没有介绍每个配置项.你可以增加一项 preference name="android-targetSdkVersion" v ...
- 九度OJ1061
//C++ sort函数的多重排序 #include <iostream> #include<algorithm> #include<string> using n ...
- Ubuntu 之 initramfs 报错解决之一
问题出现: ubuntu 更新后,编辑文件提示权限不够,并提示更新错误,重启后进入 initramfs ,仔细看提示错误有: file system check of the root filesys ...
- 蓝桥杯---数独(模拟 || dfs)
[编程题](满分33分) "数独"是当下炙手可热的智力游戏.一般认为它的起源是"拉丁方块",是大数 学家欧拉于1783年发明的. 如图[1.jpg]所示:6x6 ...
- POJ 1088 滑雪 记忆化DP
滑雪 Time Limit: 1000MS Memory Limit: 65536K Description Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激.可是为了获得速度 ...
- Iptables 防火墙开放常见的22,53,80端口
用iptables防火墙 iptables -F # 允许包从22端口进入 iptables -A INPUT -p tcp --dport 22 -j ACCEPT # 允许从22端口进入的包返回 ...
- MongoDB基本操作命令
由于工作需要,笔者这两天使用了一下MongoDB.真的很不习惯!但是确实好用,命令比mysql和sqlserver简单很多.在这里整理一些MongoDB的基本操作命令分享出来. 客户端的安装就不说了, ...
- Xcode entitlement 问题定位和解决指南
背景故事 前两天,本来一个运行正常.打包测试都没问题的XCode工程突然爆出各种奇怪的Entitlement错误: 什么签名的内容跟配置文件的不一致. 又或者 无法安装,因为签名或者配置文件的配置错误 ...
- MXNet官网案例分析--Train MLP on MNIST
本文是MXNet的官网案例: Train MLP on MNIST. MXNet所有的模块如下图所示: 第一步: 准备数据 从下面程序可以看出,MXNet里面的数据是一个4维NDArray. impo ...