用Jquery訪問WebService並返回Json的代碼第1/3頁

來源:互聯網
上載者:User

在我們的應用中一般會是這樣的,使用了jquery作為用戶端架構,ajax請求也通常返回html或者json。html這裡就不討論了。返回json一般都是搞一個handler.ashx來處理請求,拼湊字串來返回json。從而放棄了ws,因為ws返回的是xml,使用起來不方便。
所以我覺著比較完美的解決方案是讓ws返回json而且不用asp.net ajax的用戶端框是比較理想的解決方案。
通過觀測發現asp.net ajax的用戶端架構請求webservice的時候返回的是json,為什麼webservice沒有返回xml而返回了json呢?抓包分析到,關鍵在request的headers中 “Content-Type: application/json;utf-8” ,因此webservice就使用了json的序列化,應該是“System.Web.Script.Serialization.JavaScriptSerializer”這個類完成的工作,通過web.config的配置,把*.asmx交給了System.Web.Extensions.Dll。也就是這裡還是用了asp.net ajax,不過是用的服務端部分,我這裡直接用的asp.net 3.5
以上都是在囉嗦,具體的方法很簡單,看例子
ws1.asmx 複製代碼 代碼如下:using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace test2
{
/// <summary>
/// Summary description for WS1
/// </summary>
[WebService(Namespace = "http://onewww.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]

[System.Web.Script.Services.ScriptService]
public class WS1 : System.Web.Services.WebService
{

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

[WebMethod]
public TestUser CreateUser(string name,int age)
{
return new TestUser { Name = name, Age = age };
}
}

public class TestUser
{
public string Name { get; set; }
public int Age { get; set; }
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.