[C#]  WebService 使用 JSON 格式傳遞筆記 + JQuery 測試

0 2

因為一些因素,必須改寫WebService,很傳統,但是很多公司還在用..

因為XML 的關係,不想讓他傳遞資料的時候過度肥大,所以我必須要盡量乾淨的JSON..

於是開始我的改寫旅程..

0 2

首先,網路上好多好多好多文件,可能因為狀況不同,測試過許多也讓我搞混很多次..

最後有找到答案..筆記一下..

0 2

首先我開了三個不同的WebMethod 來測試三種不同的輸出..

0 2

GetUserInfoString –取得字串

GetOneUserInfo - 取得一個物件

GetUsers - 取得物件們

0 2

using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services; namespace JsonServiceSample
{ public class User
{
public string Name { get; set; }
public int Age { get; set; }
} [WebService(Namespace = "", Description = "For Donma Test")]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service1 : WebService
{ [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUserInfoString(string name, int age)
{
return name + "," + age;
} [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User GetOneUserInfo(string name, int age)
{
return (new User { Name = name, Age = age }); } [WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User[] GetUsers(string name, int age)
{
List<User> res = new List<User>();
res.Add(new User { Name = name + "1", Age = age });
res.Add(new User { Name = name + "2", Age = age }); return res.ToArray();
} } }

0 2

如這篇 0 2 [C#] Web Service 移除 xmlns 0 2 我先移除xml namespace

再來一個重點,在每一個Method 上方我都會加上

0 2

0 2

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

因為基於有時候我會需要使用GET 方式傳遞 所以我在Web Config 中加入

在system.web 中加入

0 2

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

0 2

Web.Config 全文:

0 2

<?xml version="1.0"?>

<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
--> <configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="JsonServiceSample.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
</httpHandlers> <webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost" />
<add name="Documentation" />
</protocols>
</webServices>
</system.web> <applicationSettings>
<JsonServiceSample.Properties.Settings>
<setting name="JsonServiceSample_JTestService_Service1" serializeAs="String">
<value>http://localhost:5403/Service1.asmx</value>
</setting>
</JsonServiceSample.Properties.Settings>
</applicationSettings>
</configuration>

0 2

這樣試跑一下

0 2

0 2

奇怪為什麼不是JSON ,別緊張…我們繼續使用 JQuery 來呼叫看看..

0 2

JQuery Code :

0 2

0 2

<input type="button" id="ipt1" value="test" />

   <script type="text/javascript">
   1: 0 2 

   2:        function GetInfo() {

   3:            var $res;

   4:            $.ajax({

   5:                type: "POST",

   6:                url: "Service1.asmx/GetOneUserInfo",

   7:                contentType: "application/json; charset=utf-8",

   8:                async: false,

   9:                cache: false,

  10:                dataType: 'json',

  11:                data: "{name:'當麻',age:29}",

  12:                success: function (data) {

  13:                    if (data.hasOwnProperty("d")) {

  14:                        $res = data.d;

  15:                    }

  16:                    else

  17:                        $res = data;

  18:                }

  19:            });

  20:            return $res;

  21:        }

  22:        

  23: 0 2 

  24:        $('#ipt1').click(function () {

  25:            var res = GetInfo();

  26:            alert(res.Name);

  27:        });

  28:        

  29:    

</script>

按鈕按下去之後 我讓他呼叫 GetOneUserInfo 這 method

並且使用POST

看下結果..

0 2

0 2

恩恩..的確是JSON, 但是多了一個 d 0 2 跟 __type 基本上 0 2 __type 不要去動他是不影響,但是 0 2 d 這東西必須得處理..

所以我參考這一篇 : http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/

進行改寫..實測過上面三種不同的回傳值..都 OK~~

0 2

這樣對於傳統的 WebService Reference 呼叫 0 2 WebService 不會有影響..

也可以透過JQuery 呼叫傳遞透過JSON

筆記一下..給需要的人…

C#开发的WebService使用JSON格式传递数据+Ajax测试的更多相关文章

  1. WebService使用JSON格式传递笔记+JQuery测试

    原文WebService使用JSON格式传递笔记+JQuery测试 因为一些因素,必须改写WebService,很传统,但是很多公司还在用.. 因为XML 的关系,不想让他传递数据的时候过度肥大,所以 ...

  2. SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析

    SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析 一:问题demo展示 ...

  3. WebService返回json格式数据供苹果或者安卓程序调用

    1.新建一个WebService. 2. /// <summary> /// DemoToJson 的摘要说明 /// </summary> [WebService(Names ...

  4. Android Volley获取json格式的数据

    为了让Android能够快速地访问网络和解析通用的数据格式Google专门推出了Volley库,用于Android系统的网络传输.volley库可以方便地获取远程服务器的图片.字符串.json对象和j ...

  5. SSH返回Json格式的数据

      在开发中我们经常遇到客户端和后台数据的交互,使用比较多的就是json格式了.在这里以简单的Demo总结两种ssh返回Json格式的数据 项目目录如下 主要是看 上图选择的部分 WebRoot里面就 ...

  6. PHP接收JSON格式的数据

    在API服务中,目前流行采用json形式来交互. 给前端调用的接口输出Json数据,这个比较简单,只需要组织好数据,用json_encode($array) 转化一下,前端就得到json格式的数据. ...

  7. Android读写JSON格式的数据之JsonWriter和JsonReader

    近期的好几个月都没有搞Android编程了,逐渐的都忘却了一些东西.近期打算找一份Android的工作,要继续拾起曾经的东西.公司月初搬家之后就一直没有网络,直到今日公司才有网络接入,各部门才開始办公 ...

  8. 中文格式python 打印json格式的数据中文显示问题

    废话就不多说了,开始... 平日会有这么一个应用场景,会用python去处置json格式的web API,以“ip.taobao.com”的API为例,详情见http://ip.taobao.com/ ...

  9. JSON(四)——异步请求中前后端使用Json格式的数据进行交互

    json格式的数据广泛应用于异步请求中前后端的数据交互,本文主要介绍几种使用场景和使用方法. 一,json格式字符串 <input type="button" id=&quo ...

随机推荐

  1. MySQL基础之第4章 MySQL数据类型

    4.1.整数类型 tinyint(4)smallint(6)mediumint(9)int(11)bigint(20) 注意:后面的是默认显示宽度,以int为例,占用的存储字节数是4个,即4*8=32 ...

  2. ECSHOP v2.5数据库字典

    ECSHOP v2.5 数据库字典 ECSHOP R&D Team 2007年4月16日 商品相关表 商品分类表 category 此表用来维护商品分类信息 字段名 字段描述 字段类型 默认值 ...

  3. [Everyday Mathematics]20150124

    设 $A,B$ 是同阶方阵, 满足 $AB+A+B=0$. 试证: $AB=BA$.

  4. memcache 分布式,算法实现

    memcached 虽然称为 “ 分布式 ” 缓存服务器,但服务器端并没有 “ 分布式 ” 功能.每个服务器都是完全独立和隔离的服务. memcached 的分布式,则是完全由客户端程序库实现的. 这 ...

  5. POJ 3321- Apple Tree(标号+BIT)

    题意: 给你一棵树,初始各节点有一个苹果,给出两种操作,C x 表示若x节点有苹果拿掉,无苹果就长一个. Q x查询以x为根的子树中有多少个苹果. 分析: 开始这个题无从下手,祖先由孩子的标号不能确定 ...

  6. 排序算法:七大排序算法的PHP实现

    由于最近在找工作,面试中难免会遇到一些算法题,所以就用PHP把七大排序算法都实现了一遍,也当做是一种复习于沉淀. 冒泡排序 2. 选择排序 3. 插入排序 4. 快速排序 5. 希尔排序 6. 归并排 ...

  7. 【跟我一起学Python吧】Python的包管理工具

    刚开始学习Python时,在看文档和别人的blog介绍安装包有的用easy_install, setuptools, 有的使用pip,distribute,那麽这几个工具有什么关系呢,看一下下面这个图 ...

  8. Android版本判断

    尽管Android向下兼容不好,但是一个程序还是可以在多个平台上跑的.向下兼容不好,接口改变,新的平台上不能用旧的API,旧的平台更不可能用新的API,不等于一个平台需要一个APK.可以在高版本的SD ...

  9. hive-mysql安装配置

    默认情况下,hive的元数据信息存储在内置的Derby数据中.Facebook将hive元数据存储在关系数据库 1.安装好mysql ,sudo apt-get install mysql-serve ...

  10. 32位和64位dll判断

    如何判断一个dll文件是32位还是64位? 1. 开发中经常会使用到VC的一个工具 Dependency Walker用depends.exe打开dll,文件名前有64标示的即为64位. 但是这个方式 ...