jquery实现ajax,返回json数据

来源:互联网 发布:淘宝信用贷款循环 编辑:程序博客网 时间:2024/06/05 18:02

======================================================
注:本文源代码点此下载
======================================================

jquery实现ajax可以调用几种方法

我经常用的是$get(url,data,callback,type)方法

其中url是异步请求的页面(可以是.ashx文件),data是参数,callback是回调函数,而type是返回数据的类型.type有xml,html,json,text等.

首先,页面引用jquery.js

在页面写ajax处理的js函数

function initmeeting() {

$.get("/common/meetingroom.ashx", {meetid:},function sellerlist(data){

$("#divsellerlist").html(data);

},"json");

settimeout("initmeeting()",20000);

}

function initmeeting() {

$.get("/common/meetingroom.ashx", {meetid:},function sellerlist(data){

var obj = eval( "(" + data + ")" );//转换后的json对象

$("#divsellerlist").html(obj.cellerlist);

},"html");

settimeout("initmeeting()",20000);

}

我用的返回类型是json,这样可以返回类似类的数据类型.比如{"name":"sunny d.d", "age":25}

但是在使用返回值data时,首先要转换json,通过

var obj = eval( "(" + data + ")" );//转换后的json对象

就能获得json对象.

json对象是在meetingroom.ashx文件里处理生成的

部分代码如下:

public class meetingroom : ihttphandler

{

public void processrequest(httpcontext context)

{

context.response.contenttype = "text/plain";

try

{

int meetid = xyconvert.getint32(context.request.querystring["meetid"]);

string str = "";

meetingjson meetingjson = new meetingjson();

if (meetid != 0)

{

meetingjson.cellerlist=returncellerlist(meetid);

}

str = jsonconvert.serializeobject(meetingjson);

context.response.write(str);

}

catch (exception ex) {

context.response.write(ex.message);

}

}

public class meetingjson {

string cellerlist;

public string cellerlist

{

get { return cellerlist; }

set { cellerlist = value; }

}

}

protected string returncellerlist(int meetid)

{

//省略..

}

}

返回json数据格式最重要的是使用了jsonconvert.serializeobject()方法.它可以将需要传递到客户端的数据打包,并序列化为字符串

而类jsonconvert在第三方dll文件中(newtonsoft.json.dll),引入dll就可以使用了.

注意:在.ashx页面中,想要使用session的话,直接写context.session["user"]是不行的,必须指定当前上下文可以使用session,可已实现irequiressessionstate接口,访问session

public class meetingroom : ihttphandler, irequiressessionstate

{

在中小项目中,使用这种方式实现ajax,如果是大项目里,应该有封装更好的ajax框架

绿色通道:好文要顶关注我收藏该文与我联系


======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/