当前位置: 代码迷 >> 综合 >> asp.net中 使用jquery+ashx 做ajax,json做数据传输
  详细解决方案

asp.net中 使用jquery+ashx 做ajax,json做数据传输

热度:28   发布时间:2023-12-15 12:57:23.0

一直在想在asp.net中怎么才能向在java中那样用struts那样做页面请求。

当然asp.net mvc就是类似struts的东西吧,不过还没来得及学习。

今天就用ashx来接收页面请求,并调用后台,然后返回数据给前台,用jquer .ajax提交请求,接收ashx返回的数据。

 

例子:

        例子是要实现页面加载时从数据库读取数据,并把数据放到一个下拉列表中。(因为是用ajax,就建html页面就行了,一直不喜欢aspx页面,感觉它太臃肿了。)

一.准备工作:

1.建web应用程序aspnetAjax

2.建index.htm

3.建个js文件夹,把jquery.js放进去,

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

5.在js文件夹建index.js,一般我们都是一个页面对应一个js

6.在ajax文件夹,建IndexHandler.ashx,一般一个js页面对应一个一般用户控件,这样层次感很强,也很好维护。

 

二.html页面

   html页面就简单了,我们要用ajax读后台做个下拉列表,所以页面就放个DIV就行了。其他的交给js.

 

HTML代码
<! 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 > 测试 </ 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 >
    企业性质
< div  id ="vocaspec" >   </ div >
    行业类型<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参数
             string  meth  =  context.Request.Params[ " meth " ].ToString(); 
            
// 根据参数调用不同的方法
             switch  (meth) 
            {
                
case   " load " :
                    loadjson(context);
                    
break ;
                
case   " add " :
                    add(context);
                    
break ;
            }        
       }

        
public   bool  IsReusable
        {
            
get
            {
                
return   false ;
            }
        }

       
// 页面加载方法,调用BLL,获得数据
          private   void  loadjson(HttpContext context) 
        {
            
// 实例BLL
            VocaSpecSortBLL vocaSpec  =   new  VocaSpecSortBLL();
            BLL.Owner ownerbll 
=   new  GYXMGL.BLL.Owner();
             
             DataSet ds 
=  vocaSpec.GetList( "" );
             DataSet dsindustr 
=  ownerbll.Getcharcte();

             
// 实例一个StringBuilder 用来拼接一个json数据
             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);
            
// 显示后台数据
            $( " #vocaspec " ).html(msg);
            
//  $("#industr").html(industr);
        }
    });
});

 

 

我可以看到如下数据,就是ashx中response给我们的json格式数据,现在我们要把这些数据

显示在下拉列表中。就要遍历json中的数组。

 

代码
{
" voce " :[{ " code " : " 1 " , " name " : " 农林水利 " },{ " code " : " 10 " , " name " : " 军工 " },{ " code " : " 11 " , " name " : " 农林 " },{ " 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 " : " 信息产业 " },{ " code " : " 21 " , " name " : " 化工 " },{ " code " : " 22 " , " name " : " 机械 " },{ " code " : " 23 " , " name " : " 冶金 " },{ " code " : " 24 " , " name " : " 有色金属 " },{ " code " : " 25 " , " name " : " 建材 " },{ " code " : " 26 " , " name " : " 医药 " },{ " code " : " 27 " , " name " : " 轻工 " },{ " code " : " 28 " , " name " : " 农牧产品深加工 " },{ " code " : " 3 " , " name " : " 交通 " },{ " code " : " 4 " , " name " : " 通讯 " },{ " code " : " 5 " , " name " : " 特色产业 " },{ " code " : " 6 " , " name " : " 城市基础设施 " },{ " code " : " 7 " , " name " : " 商贸流通 " },{ " code " : " 8 " , " name " : " 旅游 " },{ " code " : " 9 " , " name " : " 文体卫 " }],
" industr " :[{ " code " : " 1 " , " name " : " 国有 " },{ " code " : " 2 " , " name " : " 私人 " }]
}

 

 

修改index.js代码,遍历json数据把数据显示成下拉列表

 

 

代码
$(document).ready( function () {
    $.ajax({
        type: 
" POST " ,
        url: 
" ../ajax/NewOwnerHandler.ashx " ,
        
// json格式接收数据
        dataType:  " json " ,
        
// 指点后台调用什么方法
        data:  " meth=load " ,

        success: 
function (msg) {
             
// 实例2个字符串变量来拼接下拉列表
                var  industr  =   " <select name=\ " industr\ " ><option label=\ " --- 请选择 --- \ " ></option> " ;
               
var  vocaspec  =   " <select name=\ " vocaspec\ " ><option label=\ " --- 请选择 --- \ " ></option> " ;
              
// 使用jquery解析json中的数据
               $.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);
        }
    });
});

 

 

------------------------

ok,完结!@

 

--这个实例涉及到的知识点

1.使用一般处理程序,接收request。并可以使用response数据

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

因为一般处理程序

public class IndexHandler : IHttpHandler

他实现IHttpHandler接口

2.json数据格式

3.使用jquery ajax,并用jquery解析json数据。

  相关解决方案