//使用Prototype 1.6.1的ajax请求方法
function prototypeRequest() {
new Ajax.Request('servlet/SendInjunction', {
method : 'post',
parameters : {
company : 'example',
type : 'onePosition'
},
onSuccess : function(response) {
if (200 == response.status) {
alert("Call is success");
var content = response.responseText;
var result = response.responseText.evalJSON();
alert('content:' + content);
alert('result.code:' + result.code);
}
},
onFailure : function failureFunc(response) {
alert("Call is failed");
}
});
}
/*
* function successFunc(response) { if (200 == response.status) { alert("Call is
* success"); var content = response.responseText; alert('content:'+content); } }
*
* function failureFunc(response) { alert("Call is failed"); }
*/
//jquery 1.7.2的ajax请求方法
function jqueryRequest() {
$.post('servlet/SendInjunction', {
company : 'example',
type : 'onePosition'
}, function(data) {
alert('data:' + data);
alert(data.code);
}, "json");
}
Servlet部分:
String company = request.getParameter("company");
System.out.println("companyP:"+company);
HashMap hm=new HashMap();
hm.put("companyP",company);
hm.put("code",10000);
JsonUtil.responseJsonObject(response, hm);
responseJsonObject:
public static void responseJsonObject(HttpServletResponse response, Object obj) throws IOException{
String json;
PrintWriter out = null;
try {
json = JSONUtil.serialize(obj);
//System.out.println("json:" + json);
out = response.getWriter();
out.print(json);
out.flush();
} catch (JSONException e) {
e.printStackTrace();
}finally{
if(out != null){
out.close();
}
}
}
用到了googlecode中的jsonplugin.jar