天天看點

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;

結果 :

[{"typeid":"9","typename":"體育/運動"},{"typeid":"8","typename":"政治/軍事"},{"typeid":"7","typename":"動漫/幽默"},{"typeid":"6","typename":"小說/文學"},{"typeid":"5","typename":"成功/勵志"}]