您的位置:首页 > Web前端 > JavaScript

使用JSON向服务器发送数据

2007-03-28 15:54 609 查看
  Ajax中可以使用xml作为参数发送给服务器,除了XML还可以使用JSON(http://www.json.org/json-zh.html
  XML的一个替代方法是JSON,JSON是一种文本格式,它独立于具体语言,JSON建立在以下两种数据结构基础上:
  名/值对集合,在不同的语言中,被实现为一个对象、记录、结构或字典
  值的有序表,在大部分语言中,实现为数组

JSON可以做为异构系统之间的一种数据互换格式。
JSON对象是名/值对的无序集合({},使用“:”分隔),JSON数组是一个有序的值集合([],使用“,”分隔)

如下就是一个JSON格式的数据:

var employee = {
“firstName” : John
, “lastName” : Doe
, “employeeNumber : 123
, ”title” : “Accountant”
}

可是使用标准点记法使用对象的属性:

var lastName = employee.lastName; //Access the last Name
var title = employee.title; //Access the title
employee.employeeNumber = 456; //Change the employee number

通过JSON.js的carAsJSON=JSON.stringify(car)方法把一个对象转换成JSON格式,然后send(carAsJSON)发送,在Java Servlet端采用new JSONObject(carAsJSON)方法生成JSONObject对象,然后可以使用其getInt、getString等方法获取其中的值。

如下一个简单例子:
jsonExample.html:(其中需要到JSON网站下载json.js文件)




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>


<head>


<title>jsonExample.html</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()




...{


var car = getCarObject();




//Use the JSON JavaScript library to stringify the Car object


var carAsJSON = JSON.stringify(car);


alert("Car object as JSON: " + carAsJSON);




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(carAsJSON);


}




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);


}




function getCarObject()




...{


return new Car("Dodge", "Coroner R/T", 1969, "yellow");


}




function Car(make, model, year, color)




...{


this.make = make;


this.model = model;


this.year = year;


this.color = color;


}


</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>



JSONExample.java:(其中需要到JSON网站下载org.json.JSONObject包)


package com.asima.chap3;




import java.io.BufferedReader;


import java.io.IOException;


import java.text.ParseException;




import javax.servlet.ServletException;


import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpServletResponse;




import org.json.JSONObject;






/** *//**


*


* @author asima


* @date 2007-2-4


*/


public class JSONExample extends HttpServlet




...{


protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException




...{


String json = readJSONStringFromRequestBody(request);




//Use the JSON-Java binding library to create a JSON object in Java


JSONObject jsonObject = null;


try




...{


jsonObject = new JSONObject(json);


}


catch ( ParseException pe)




...{


System.out.println("ParseException: " + pe.toString());


}




String responseText = "You have a " + jsonObject.getInt("year") + " " +


jsonObject.getString("make") + " " + jsonObject.getString("model") + " " +


" that is " + jsonObject.getString("color") + " in color.";




response.setContentType("text/xml");


response.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 in readJSONStringFromRequestBody: " + e.toString());


}


return json.toString();


}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: