众所周知,ajax可通过直接写源码实现,但有点繁琐,现在流行的ajax框架都集成了ajax的功能,而且写起来非常简单方便。当然mootools也不例外。
mootools的Request实现了对XMLHttpRequest的功能包装类,下面是我写的小例子:
js:
function testPing(){
var url = document.getElementById("url").value;
var pingRequest = new Request({
method: "post",
url: "../site/ping.do",
onSuccess: function(responseText){
if(responseText=="success"){
document.getElementById("pingDiv").innerHTML ="此url可ping通";
}
else{
document.getElementById("pingDiv").innerHTML ="此url不能ping通";
}
},
onFailure: function(){
document.getElementById("pingDiv").innerHTML ="此url不能ping通";
}
});
pingRequest.send("url="+ url);
}
html:
<input type="text" id="url" name="${status.expression}" value="$!{status.value}"/>
<input type="button" name="ping" value="测试链接" onClick="testPing()" />
<div style="color: #f5001D;" id="pingDiv"></div>
java代码:
@RequestMapping("/site/ping.do")
public void ping(@RequestParam("url") String url,ModelMap model, HttpServletResponse response) throws IOException {
AjaxUtil ajaxUtil = new AjaxUtil();
try {
Ping ping = new Ping();
boolean pingFlag = ping.pingServer(url,5);
if(pingFlag){
ajaxUtil.ajaxOutput(response, "success");
}else{
ajaxUtil.ajaxOutput(response, "error");
}
} catch (Exception e) {
ajaxUtil.ajaxOutput(response, e.toString());
}
}
public class AjaxUtil {
/**
* 将对象转化为JSON字符串
* @param object
* @return
*/
public String convert2JSONString(Object object) {
JSONArray jsonObject = JSONArray.fromObject(object);
return jsonObject.toString();
}
/**
* 返回AJAX调用结果
* @param response
* @param outputString
* @throws java.io.IOException
*/
public void ajaxOutput(HttpServletResponse response, String outputString) throws IOException {
response.setContentType("text/html; charset=utf-8");
response.getWriter().write(outputString);
response.getWriter().flush();
}
}