JSP:
<head>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
var http_request = false;
function send_request(url)
{
http_request = false;
if(window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType(‘text/xml‘);
}
}else if (window.ActiveXObject)
{
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!http_request)
{
window.alert("不能创建XMLHttpRequest对象实例.");
return false;
}
http_request.onreadystatechange = processRequest;
http_request.open("GET", url, true);
http_request.send(null);
}
function processRequest()//返回结果处理函数
{
if (http_request.readyState == 4)
{
if (http_request.status == 200) {
var f=JSON.parse(http_request.responseText);
//f中存有json格式的数据。通过f.attribute就可以访问json
中的内容了
} else
{
alert("您的网络有异常");
}
}
}
function getFunction(){
send_request(‘/***.do?‘);
}
</head>
服务端:
import org.json.JSONException;
import org.json.JSONObject;
public class GetFunctionAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonObj=new JSONObject();
try {
jsonObj.put("name", "**");
//……
} catch (JSONException e) {
e.printStackTrace();
}
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
try {
PrintWriter out=response.getWriter();
out.println(jsonObj.toString());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}