ASP.NETでJSONデータを作成するサンプル
ASP.NETで作成されたJSONデータを非同期通信で取得して表示している。
テスト実行
Java Script
JsonTest.aspx
EncodeForAjax.cs
JsonTest.aspxをブラウザで表示したとき
ASP.NETで作成されたJSONデータを非同期通信で取得して表示している。
テスト実行
Java Script
$.ajax({
type: "POST",
url: 'http://localhost:4236/test/JsonTest.aspx',
cache: false,
async : true,
dataType: "json",
success: function( data ) {
//▼非同期通信成功時
$.each(data,function( i, ent ) {
var tr=""+ent.dekigoto+
" "+ent.jinbutu +
" "+ent.nen +
" ";
$('#test_table tbody').append(tr);
});
},
error: function( data ) {
alert("ajax失敗");
}
});
JsonTest.aspx
Response.AppendHeader("Access-Control-Allow-Origin", "*");//クロスドメイン通信を許可する。
string dekigoto;
string jinbutu;
string nen;
dekigoto="六波羅探題";
jinbutu="北条泰時";
nen="1221";
//文字化けを防ぐためのエンコードを行う。
dekigoto = EncodeForAjax.HtmlEncode(dekigoto);
jinbutu = EncodeForAjax.HtmlEncode(jinbutu);
//Dictionary型のサンプルデータを作成。
Dictionary map = new Dictionary();
map.Add("dekigoto", dekigoto);
map.Add("jinbutu", jinbutu);
map.Add("nen", nen);
//Hashtable型のサンプルデータを作成。
Hashtable map2 = new Hashtable();
map2.Add("dekigoto", "syokyunoran");
map2.Add("jinbutu", "gotoba_jokyo");
map2.Add("nen", 1221);
Response.Clear();//HTML側をクリア。
Response.ContentType = "application/json";//コンテンツタイプを指定。
Response.Write("[");
//「"キー名"="値"」の形式に変換して出力。
Response.Write(new JavaScriptSerializer().Serialize(map));
Response.Write(",");
Response.Write(new JavaScriptSerializer().Serialize(map2));
Response.Write("]");
Response.End();
EncodeForAjax.cs
public class EncodeForAjax
{
static public string HtmlEncode(string text)
{
char[] chars = HttpUtility.HtmlEncode(text).ToCharArray();
StringBuilder result = new StringBuilder(text.Length + (int)(text.Length * 0.1));
foreach (char c in chars)
{
int value = Convert.ToInt32(c);
if (value > 127)
result.AppendFormat("{0};", value);
else
result.Append(c);
}
return result.ToString();
}
}
JsonTest.aspxをブラウザで表示したとき
[{"dekigoto":"六波羅探題","jinbutu":"北条泰時","nen":"1221"},{"jinbutu":"gotoba_jokyo","dekigoto":"syokyunoran","nen":1221}]