脚本中加入 function getXML(){ //局部请求的地址 var url="priceAction"; //创建的 对象名(这个对象名其实在这里并没有被使用过,当对象一被创建,局部请求就已经发出,所以这里不需要使用这个对象名,它完全可以是匿名的) var myAjax = new Ajax.Request( url, { method:'post', //请求方法 onComplete:showResponse, //回调函数 asynchronous:true //是否异步 } ); } //回调函数,注意这个回调函数是有参数,用于接收返回的信息 function showResponse(xmlrequest){ gx.innerHTML=xmlrequest.responseText; } 页面中加入 xml:
可以看到请求被正确发出了,没有浏览器的判断,没有手写的open函数,很简洁
同一页面可以很方便的使用多个XmlHttpRequest对象来进行异步请求 脚本中再加入 function getXML2(){ var url="priceAction"; var myAjax = new Ajax.Request( url, { method:'post', onComplete:showResponse2, asynchronous:true } ); }
function showResponse2(xmlrequest2){ gx2.innerHTML=xmlrequest2.responseText; } 页面中 xml2:
/** * Constructor of the object. */ public PriceAction() { super(); }
/** * Destruction of the servlet.
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here }
/** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("");
Random rand = new Random(System.currentTimeMillis()); out.write(rand.nextInt(10)+"$"+rand.nextInt(10)+"$"+rand.nextInt(10)); //System.out.println(rand.nextInt(10)+"$"+rand.nextInt(10)+"$"+rand.nextInt(10)); out.flush(); out.close(); }
/** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response); }
/** * Initialization of the servlet.
* * @throws ServletException if an error occure */ public void init() throws ServletException { // Put your code here }