上一篇【使用JQuery來傳遞JSON字串】介紹了如何在前端傳遞JSON物件至後端接收,這篇主要介紹如何從後端組出JSON物件,回傳至前端接收。
接續上一篇範例,我們這篇點查詢後,將使用者的資訊利用JSON.NET組合JSON格式,丟回前端做處理。
.ashx
後端我們一樣用泛型處理常式來處理,有一個我們自行定義的User class,裡面有User的Name,和他所會的Skill,依抓資料的來源取得資料後組成List<string>,只要透過Json.NET的SerializeObject function就可以輕易的將List<Object>轉成Json字串。
.aspx
回傳前端console.log來看,會看到一個object的Array,接著只要處理顯示畫面就可以了,非常的容易 !!
完整程式碼
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyMVC.WebFrom.Json
{
/// <summary>
/// ReturnJsonHandler 的摘要描述
/// </summary>
public class ReturnJsonHandler : IHttpHandler
{
public class User
{
public string UserName { get; set; }
public List<string> Skill { get; set; }
}
public void ProcessRequest(HttpContext context)
{
List<User> UserList = GetUser();
string ReturnString = JsonConvert.SerializeObject(UserList);
context.Response.Write(ReturnString);
}
private List<User> GetUser()
{
List<User> UserList = new List<User>();
User User1 = new User();
User1.UserName = "User1";
User1.Skill = new List<string>() { "PHP", "ASP.NET" };
User User2 = new User();
User2.UserName = "User2";
User2.Skill = new List<string>() { "JSP", "ASP.NET" };
UserList.Add(User1);
UserList.Add(User2);
return UserList;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetJson.aspx.cs" Inherits="MyMVC.WebFrom.Json.GetJson" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../../Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#btn_search').click(function () {
$.ajax({
url: 'ReturnJsonHandler.ashx',
data: {}, //將陣列轉成Json
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
var string = "<div>";
string = data[i].UserName+":";
for (var k = 0; k < data[i].Skill.length; k++) {
string += data[i].Skill[k];
}
string += "<div/>";
$('#UserList').append(string);
}
}
});
});
});
</script>
<form id="form1" runat="server">
<div>
<input type="button" id="btn_search" value="查詢" />
<div id="UserList">
</div>
</div>
</form>