ASP.NET(AJAX+JSON)實(shí)現(xiàn)對(duì)象調(diào)用

2022-05-17 14:27 更新

客戶端 

代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ASP.NETA_JAX.aspx.cs" Inherits="_Default" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<script type="text/jscript"> 
function CallServer() { 
//JSON發(fā)送對(duì)象 
ServerSum("{name:'linyijia',age:'21'}"); 
} 
function GetRegister(rg, contex) { 
document.getElementById("TxtRegister").value=rg; 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<br /> 
用戶名:<input id="TxtNum1" type="text" /> 
<br /> 
服務(wù)器:<input id="TxtRegister" type="text" /><br /> 
<button id="SumBtn" type="button" onclick="CallServer()">登錄</button> 
</div> 
</form> 
</body> 
</html> 

服務(wù)器

代碼如下:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.Script.Serialization; 
public partial class _Default : System.Web.UI.Page ,ICallbackEventHandler 
{ 
Users u = null; 
protected void Page_Load(object sender, EventArgs e) 
{ 
//回調(diào)GetRegister方法 
string CallBackFun = Page.ClientScript.GetCallbackEventReference(this,"arg","GetRegister","context"); 
//創(chuàng)建ServerSum方法,在客戶端調(diào)用的時(shí)候就,會(huì)回調(diào)GetRegister方法,把參數(shù)傳給RaiseCallbackEvent(string eventArgument ),最后通過 
//GetCallbackResult()方法把返回值傳給客戶端 
string RegisterFun = string.Format("function ServerSum(arg,context){{{0};}}",CallBackFun); 
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"ServerSum",RegisterFun,true); 
} 
string mssage = string.Empty; 
#region ICallbackEventHandler 成員 
public string GetCallbackResult() 
{ 
return "服務(wù)器:你好,你的用戶名為:" + u.Name + "你的年齡為" + u.Age; 
} 
public void RaiseCallbackEvent(string eventArgument) 
{ 
JavaScriptSerializer js = new JavaScriptSerializer(); 
u =js.Deserialize<Users>(eventArgument); 
} 
#endregion 
} 

Users類 

代碼如下:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
/// <summary> 
///User 的摘要說明 
/// </summary> 
public class Users 
{ 
string name; 
public string Name 
{ 
get { return name; } 
set { name = value; } 
} 
string age; 
public string Age 
{ 
get { return age; } 
set { age = value; } 
} 
} 
原理: 

使用JSON向服務(wù)器發(fā)送一個(gè)對(duì)象,服務(wù)器通過實(shí)現(xiàn) ICallbackEventHandler接口后,重寫GetCallbackResult和RaiseCallbackEvent方法,在回調(diào)的時(shí)候,在RaiseCallbackEvent方法中反序列化JSON,并在GetCallbackResult把結(jié)果返回給客戶端.

asp.net中使用jquery+ashx做ajax,json做數(shù)據(jù)傳輸

一、準(zhǔn)備工作

1.建web應(yīng)用程序aspnetAjax

2.建index.htm

3.建個(gè)js文件夾,把jquery.js放進(jìn)去,

4.建ajax文件夾,里面放ashx

5.在js文件夾建index.js,一般我們都是一個(gè)頁面對(duì)應(yīng)一個(gè)js

6.在ajax文件夾,建IndexHandler.ashx,一般一個(gè)js頁面對(duì)應(yīng)一個(gè)一般用戶控件,這樣層次感很強(qiáng),也很好維護(hù)。

二、html頁面

html頁面就簡(jiǎn)單了,我們要用ajax讀后臺(tái)做個(gè)下拉列表,所以頁面就放個(gè)DIV就行了。其他的交給js.

代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>測(cè)試</title>
    <script src="js/jquery-1.2.3-intellisense.js" type="text/javascript"></script>
    <script src="js/index.js" type="text/javascript"></script>
</head>
<body>
    企業(yè)性質(zhì)<div id="vocaspec"> </div>
    行業(yè)類型<div id="industr"> </div>      
</body>
</html>


編寫IndexHandler.ashx代碼

代碼:

namespace aspnetAjax.ajax
{
    /// <summary>
    /// $codebehindclassname$ 的摘要說明
    /// </summary>

    public class IndexHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
           context.Response.ContentType = "application/json";
           //接收提交過來的meth參數(shù)
            string meth = context.Request.Params["meth"].ToString(); 
            //根據(jù)參數(shù)調(diào)用不同的方法
            switch (meth) 
            {
                case "load":
                    loadjson(context);
                    break;
                case "add":
                    add(context);
                    break;
            }        
       }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
       //頁面加載方法,調(diào)用BLL,獲得數(shù)據(jù)
         private void loadjson(HttpContext context) 
        {
            //實(shí)例BLL
            VocaSpecSortBLL vocaSpec = new VocaSpecSortBLL();
            BLL.Owner ownerbll = new GYXMGL.BLL.Owner();
             
             DataSet ds = vocaSpec.GetList("");
             DataSet dsindustr = ownerbll.Getcharcte();
             //實(shí)例一個(gè)StringBuilder 用來拼接一個(gè)json數(shù)據(jù)
             StringBuilder sbvoca = new StringBuilder();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                sbvoca.Append("{\"voce\":[");
                int i = 1;
                int count = ds.Tables[0].Rows.Count;
                foreach (DataRow dr in ds.Tables[0].Rows) 
                {
                    if (i == count)
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"}");
                    }
                    else
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"},");
                    }
                    i++;
                }
                sbvoca.Append("]");
            }
            if (dsindustr != null && dsindustr.Tables[0].Rows.Count > 0) 
            {
                sbvoca.Append(",\"industr\":[");
                int i = 1;
                int count = dsindustr.Tables[0].Rows.Count;
                foreach (DataRow dr in dsindustr.Tables[0].Rows)
                {
                    if (i == count)
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"}");
                    }
                    else 
                    {
                        sbvoca.Append("{\"code\":\"" + dr[0] + "\",\"name\":\"" + dr[1] + "\"},");
                    }
                    i++;
                }
                sbvoca.Append("]");
            }
            sbvoca.Append("}");
            context.Response.Write(sbvoca.ToString());
            
            context.Response.End();
        }
    }
}

我們把index.js改下

代碼

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "../ajax/NewOwnerHandler.ashx",
        //我們用text格式接收
        dataType: "text",
        data: "meth=load",
        success: function(msg) {
            alert(msg);
            //顯示后臺(tái)數(shù)據(jù)
            $("#vocaspec").html(msg);
            // $("#industr").html(industr);
        }
    });
});

看到如下數(shù)據(jù),就是ashx中response給我們的json格式數(shù)據(jù),現(xiàn)在我們要把這些數(shù)據(jù)

顯示在下拉列表中。就要遍歷json中的數(shù)組。

代碼:

{
"voce":[{"code":"1","name":"農(nóng)林水利"},{"code":"10","name":"軍工"},{"code":"11","name":"農(nóng)林"},{"code":"12","name":"水利(電)"},{"code":"13","name":"水電站"},{"code":"14","name":"輸變線"},{"code":"15","name":"煤礦"},{"code":"16","name":"氣田"},{"code":"17","name":"公路"},{"code":"18","name":"鐵路"},{"code":"19","name":"民航"},{"code":"2","name":"能源"},{"code":"20","name":"信息產(chǎn)業(yè)"},{"code":"21","name":"化工"},{"code":"22","name":"機(jī)械"},{"code":"23","name":"冶金"},{"code":"24","name":"有色金屬"},{"code":"25","name":"建材"},{"code":"26","name":"醫(yī)藥"},{"code":"27","name":"輕工"},{"code":"28","name":"農(nóng)牧產(chǎn)品深加工"},{"code":"3","name":"交通"},{"code":"4","name":"通訊"},{"code":"5","name":"特色產(chǎn)業(yè)"},{"code":"6","name":"城市基礎(chǔ)設(shè)施"},{"code":"7","name":"商貿(mào)流通"},{"code":"8","name":"旅游"},{"code":"9","name":"文體衛(wèi)"}],
"industr":[{"code":"1","name":"國(guó)有"},{"code":"2","name":"私人"}]
}

修改index.js代碼,遍歷json數(shù)據(jù)把數(shù)據(jù)顯示成下拉列表

代碼:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "../ajax/NewOwnerHandler.ashx",
        //json格式接收數(shù)據(jù)
        dataType: "json",
        //指點(diǎn)后臺(tái)調(diào)用什么方法
        data: "meth=load",
        success: function(msg) {
             //實(shí)例2個(gè)字符串變量來拼接下拉列表
               var industr = "<select name=\"industr\"><option label=\"---請(qǐng)選擇---\"></option>";
               var vocaspec = "<select name=\"vocaspec\"><option label=\"---請(qǐng)選擇---\"></option>";
              //使用jquery解析json中的數(shù)據(jù)
               $.each(msg.voce, function(n, value) {
                     vocaspec += ("<option value=\"" + value.code + "\" label=\"" + value.name + "\">");
                     vocaspec += ("</option>");
                    });
                $.each(msg.industr, function(n, value) {
                     industr += ("<option value=\"" + value.code + "\" label=\"" + value.name + "\">");
                      industr += ("</option>");
                   });
             industr += ("</select>");
             $("#vocaspec").html(vocaspec);
            $("#industr").html(industr);
        }
    });
});

這個(gè)實(shí)例涉及到的知識(shí)點(diǎn)

1、使用一般處理程序,接收request。并可以使用response數(shù)據(jù)

string meth = context.Request.Params["meth"].ToString();

因?yàn)橐话闾幚沓绦?/p>

public class IndexHandler : IHttpHandler

他實(shí)現(xiàn)IHttpHandler接口

2、json數(shù)據(jù)格式

3、使用jquery ajax,并用jquery解析json數(shù)據(jù)。 

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)