您的位置:首页 > Web前端 > JQuery

asp.net 中 Json、Jquery、Post简单使用

2012-03-26 14:57 483 查看
前台取得数据:

//数据库中有 typeid 和 typename 字段

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

<script type="text/javascript">

var json;

$(document).ready(function () { //ready-start

$.post( //post请求开始

"/test1.ashx", { data1: new Date() }, function (text) {

json =JSON.parse(text); //字符串转换为JSON格式,重要!

var html = '';

$.each(json, function (Index, Item) {//遍历每条数据

html += '<div class="comment"><h4>index:' +Index + ",typeid:" +Item['typeid'] + ',typename:'
+ Item['typename'] + '</div>';

//或 html += '<div class="comment"><h4>index:' +Index + ",typeid:" +Item.typeid + ',typename:' +Item.typename
+ '</div>';

})

$('#testdiv').html(html);//给层 testdiv 赋值

$('#jsondata').html(text);//给层 jsondata 赋值

}

); //post请求结束

}); //ready-End

</script>

后台响应请求:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using Newtonsoft.Json;// 引用Newtonsoft.Json,版本3.5

namespace EbookShop

{

/// <summary>

/// test1 的摘要说明

/// </summary>

public class test1 : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "text/plain";

BLL.booktypeBLL bll = new BLL.booktypeBLL();

DataTable dt = bll.GetPagedList(1,5,"","typeid desc").Tables[0];//查询数据库中的表数据

string str =
JsonConvert.SerializeObject(dt);//转换为json格式的字符串

//JsonSerializer jsonSerializer = new JsonSerializer();

//jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

context.Response.Write(str);

}

public bool IsReusable

{

get

{

return false;

}

}

}

}

结果 :

index:0,typeid:9,typename:体育/运动

index:1,typeid:8,typename:政治/军事

index:2,typeid:7,typename:动漫/幽默

index:3,typeid:6,typename:小说/文学

index:4,typeid:5,typename:成功/励志

[{"typeid":"9","typename":"体育/运动"},{"typeid":"8","typename":"政治/军事"},{"typeid":"7","typename":"动漫/幽默"},{"typeid":"6","typename":"小说/文学"},{"typeid":"5","typename":"成功/励志"}]

欢迎大家到我的新浪博客学习交流: http://blog.sina.com.cn/pukuimin
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: