26
2012
03

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

前台取得数据:

//数据库中有 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://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。