示例代碼下載:
本文中所包含的內容如下:
* 準備
* 一般處理程序/ashx
* WebService/asmx準備
如果希望通過 ashx 或者 asmx 來返回 JSON, 那么需要引用程序集 System.Web.Extensions.dll, 在 .NET 3.5, 4.0 中已經默認包含. 對于 .NET 2.0, 3.0, 需要安裝 ASP.NET 2.0 AJAX, 可以在 ?displaylang=en&id=883 下載.
一般處理程序/ashx
使用一般處理程序返回 JSON, 對于不同版本的 .NET 都是類似, 請看下面的 handler.ashx 的代碼:
復制代碼 代碼如下:
<%@ WebHandler Language="C#" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
public class handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
context.Response.Cache.SetNoStore ( );
string name = context.Request["name"];
SortedDictionary<string, object> values = new SortedDictionary<string, object>();
values.Add("message",
string.IsNullOrEmpty(name) ? "無名氏" :
string.Format("你好 {0}, {1}", name, DateTime.Now));
context.Response.Write(new JavaScriptSerializer().Serialize(values));
}
public bool IsReusable
{
get { return false; }
}
}
復制代碼 代碼如下:
function(data){
alert(data.message);
}
復制代碼 代碼如下:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true">
<assemblies>
<add
assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<pages/>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx"
type="System.Web.Script.Services.ScriptHandlerFactory"
validate="false"/>
</httpHandlers>
</system.web>
</configuration>
復制代碼 代碼如下:
<%@ WebService Language="C#" CodeBehind="~/App_Code/webservice.cs" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;
[WebService ( Namespace = "http://tempuri.org/" )]
[WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 )]
[ScriptService]
public class webservice : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod]
public SortedDictionary<string, object> Save ( string name )
{
this.Context.Response.Cache.SetNoStore ( );
SortedDictionary<string, object> values = new SortedDictionary<string, object> ( );
values.Add ( "message",
string.IsNullOrEmpty ( name ) ? "無名氏" :
string.Format ( "你好 {0}, {1}", name, DateTime.Now ) );
return values;
}
}
復制代碼 代碼如下:
function(data){
alert(data.message);
}
function(data){
alert(data.d.message);
}
JQueryElement 是開源共享的代碼, 可以在 頁面下載 dll 或者是源代碼.
實際過程演示: , 建議全屏觀看.
歡迎訪問 panzer 開源項目, , 其中包含了 IEBrowser 控制 WebBrowser 執行各種 js 和 jQuery 腳本以及錄制功能 和 jQueryUI 的 Asp.net 控件 JQueryElement.
新聞熱點
疑難解答
圖片精選