簡単なJSON+AJAX


最近システムを徹底的に整理して、整理する時意外にも以前のプロジェクトを発見して、練習問題.だからみんなに見せてあげます.記念にもします.めまいが
内容は次のとおりです.
ここはjsonです.js(index.jspに置いて、必ずだからjsの最初の導入に置くことを覚えています)、json.jar(binの下に置く).
1:まずjsファイルを作成します
内容は次のとおりです.
     var xmlHttp;
function  createXMLHttpRequest()  {
  if  (window.ActiveXObject)  {
     xmlHttp  =   new  ActiveXObject("Microsoft.XMLHTTP");
  }  
  else   if  (window.XMLHttpRequest)  {
     xmlHttp  =   new  XMLHttpRequest();
  } 
} 
//  Person      
function Person(name,age,gender,birthday){
	this.age = age;
	this.gender = gender;
	this.name = name;
	this.birthday = birthday;
}
//    Person   
function getPerson(){
	return new Person("coco",25,true,"1988-08-08");
}
//  ajax  
function doJSON(){
   var  person  =  getPerson();
   
   //  json.js   stringify()   person     Json    
   var  personAsJSON  =  JSON.stringify(person);
   alert( " Car object as JSON:
" + personAsJSON); var url = "JSONExample?timeStamp="+new Date().getTime(); createXMLHttpRequest(); xmlHttp.open("POST",url,true ); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader("Content-Type" ,"application/x-www-form-urlencoded"); xmlHttp.send(personAsJSON); } function handleStateChange() { if (xmlHttp.readyState == 4 ) { if (xmlHttp.status == 200 ) { parseResults(); } } } function parseResults() { var responseDiv = window.document.getElementById("responseDiv"); var content = xmlHttp.responseText responseDiv.value = content; }

 
 
以下、処理するサーブレット
 
 
public class JSONExample extends HttpServlet{
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String json  =  readJSONStringFromRequestBody(req);
        
        // Use the JSON-Java binding library to create a JSON object in Java 
        JSONObject jsonObject  =   null ;
        String responseText = null;
        try{
           // json      JsonObject  
           jsonObject  =   new  JSONObject(json);
           String gender = jsonObject.getBoolean("gender")?" ":" ";
           responseText  =   "You name is  "   +  jsonObject.getString( "name" )  +   " age is  " 
           +  jsonObject.getInt( "age" )  +   "  gender is "   + gender
           +  "  birthday is  "   +  jsonObject.getString( "birthday" );
           System.out.println("responseText="+responseText);
        } 
         catch (Exception pe)  {
           System.out.println( " ParseException:  "   +  pe.toString());
        } 
        //     ,       
        resp.setCharacterEncoding("utf-8");
        resp.setContentType( "text/xml" );
        resp.getWriter().print(responseText);
	}

	//         
	private  String readJSONStringFromRequestBody(HttpServletRequest request) {
        StringBuffer json  =   new  StringBuffer();
        String line  =   null ;
        try   {
            BufferedReader reader  =  request.getReader();
            while ((line  =  reader.readLine())  !=   null )  {
                json.append(line);
            } 
        } 
          catch (Exception e)  {
            System.out.println( "Error reading JSON string:  "   +  e.toString());
        } 
         return  json.toString();
    } 
}