在.NET中結合AJAX使用JSON

例子和<<Ajax基礎教程>>中的那個例子類似,不過書中的例子是用java寫的server端code,我這裏用.net再寫一次:

我就直接把客戶端的code帖出來了:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    
<title>無標題頁</title>

    
<script type="text/javascript" src="json.js"></script>

    
<script type="text/javascript">
var xmlHttp;

function createXMLHttpRequest() 
{
    
if (window.ActiveXObject) 
    
{
        xmlHttp 
= new ActiveXObject("Microsoft.XMLHTTP");
    }
 
    
else if (window.XMLHttpRequest) 
    
{
        xmlHttp 
= new XMLHttpRequest();
    }

}
  

function doJSON()
{
    createXMLHttpRequest();
    
var car=getCarObject();    
    
//alert("Car object as JSON: "+car.toJSONString());
    xmlHttp.onreadystatechange=handleStateChange;
    xmlHttp.open(
"post","dojson.aspx",true);
    xmlHttp.setRequestHeader(
"content-type","application/x-www-form-urlencode");
    xmlHttp.send(car.toJSONString());
}


function getCarObject()
{
    
return new Car("Dodge","Coronet R/T",1968,"yellow");    
}


function Car(make,model,year,color)
{
    
this.Make=make;
    
this.Model=model;
    
this.Year=year;
    
this.Color=color;
}

    
function handleStateChange() 
{
    
if(xmlHttp.readyState == 4
    
{
        
if(xmlHttp.status == 200
        
{
            parseResults();
        }

    }

}


function parseResults() {

    
var responseDiv = document.getElementById("serverResponse");
    
if(responseDiv.hasChildNodes()) 
    
{
        responseDiv.removeChild(responseDiv.childNodes[
0]);
    }

    
    
var responseText = document.createTextNode(xmlHttp.responseText);
    responseDiv.appendChild(responseText);
}


    
</script>

</head>
<body>
    
<br />
    
<br />
    
<form action="#">
        
<input type="button" value="Click here to send JSON data to the server" onclick="doJSON();" />
    
</form>
    
<h2>
        Server Response:
</h2>
    
<div id="serverResponse">
    
</div>
</body>
</html>

 這上面ajax的部分就不再詳解了.

重點在server端:

我在這裏實現和原書中同樣的目的,同樣帖出全部的code: 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public partial class dojson : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
byte[] b = new byte[this.Request.InputStream.Length];
        
this.Request.InputStream.Read(b, 0, b.Length);
        
string s = System.Text.Encoding.Default.GetString(b);        
        Car car 
= (Car)JavaScriptConvert.DeserializeObject(s, typeof(Car));
        
string str = "";
        str 
= "You have a " + car.Year + " " + car.Make + " " + car.Model + " that is " + car.Color + " in color.";
        
this.Response.Write(str);
        
this.Response.Flush();
        
this.Response.Close();
    }


    
private class Car
    
{
        
public Car()
        
{ }
        
private string make;

        
public string Make
        
{
            
get return make; }
            
set { make = value; }
        }


        
private string model;

        
public string Model
        
{
            
get return model; }
            
set { model = value; }
        }


        
private int year;

        
public int Year
        
{
            
get return year; }
            
set { year = value; }
        }


        
private string color;

        
public string Color
        
{
            
get return color; }
            
set { color = value; }
        }

    }

}

 

這裏用了最近的Newtonsoft.Json.dll,是2007-3-20的,也就是Json.NET 1.2版,詳見http://www.newtonsoft.com/blog/

主要用了一個反序列化,JavaScriptConvert.DeserializeObject,對在javascript中的object另外在C#裏定義一個class,利用JavaScriptConvert.DeserializeObject方法做反序列化,可以從json的字符串裏得到Car的一個實例,這樣就可以完成下面的工作了.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章