JSON是JavaScript對象與伺服器對象互動的一種技術手段,JavaScript
中使用function構建函數類,在.net伺服器方使用JSON類庫解析
此JavaScript函數類達到JavaScript與伺服器傳遞資料的目的.
常被用於Ajax中.
請求頁send_json_request.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="send_json_request.aspx.cs" Inherits="Ajax_send_json_request" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script language="javascript" src="json.js"></script>
<script language="javascript">
var xmlHttp;
function createXMLHttp()
{
if (window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
function user(name,pwd)
{
this.Name = name;
this.Pwd = pwd;
}
function getUser()
{
return new user(document.getElementById('txtName').value,document.getElementById('txtPwd').value);
}
function getUserInfo()
{
var user1 = getUser();
var json_user1 = JSON.stringify(user1);
createXMLHttp();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("POST","send_json_response.aspx?timeStamp="+new Date().getTime(),true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(json_user1);
return false;
}
function handleStateChange()
{
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<div>
使用者名稱:
<input type="text" name="txtName" id="txtName">
密碼:
<input type="text" name="txtPwd" id="txtPwd">
<input type="button" name="Submit" value="查看使用者資訊" onClick="return getUserInfo();">
</div>
</form>
</body>
</html>
響應頁send_json_response.aspx:
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using NUnit.Framework;
public partial class Ajax_send_json_response : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string str = string.Empty;
byte[] bytes = Request.BinaryRead(Request.TotalBytes);
str = System.Text.Encoding.UTF8.GetString(bytes);
User u = (User)JavaScriptConvert.DeserializeObject(str, typeof(User));
if (u.Name.ToLower().Equals("admin") && u.Pwd.ToLower().Equals("admin"))
{
Response.Write("管理員");
}
else if (u.Name.ToLower().Equals("user") && u.Pwd.ToLower().Equals("user"))
{
Response.Write("普通使用者");
}
else
{
Response.Write("輸入錯誤");
}
}
new class User
{
private string name;
private string pwd;
public string Name
{
set { this.name = value; }
get { return this.name; }
}
public string Pwd
{
set { this.pwd = value; }
get { return this.pwd; }
}
}
}
注:上例需要json.js,Newtonsoft.Json.dll,nunit.framework.dll.