ajax异步传输实例java_AJAX与java servlet结合使用的异步传输实例

AJAX与java servlet结合使用的异步传输实例。html页面代码(使用了jquery):

-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

//定义一个全局的XmlHttpRequest类型的变量

var xmlHttp = false;

//创造一个XmlHttpRequest对象

function createXmlHttpRequest() {

/* Create a new XMLHttpRequest object to talk to the Web server */

/*@cc_on @*/

/*@if (@_jscript_version >= 5)

try {

xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

} catch (e) {

try {

xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (e2) {

xmlHttp = false;

}

}

@end @*/

if (!xmlHttp && typeof XMLHttpRequest != ‘undefined’) {

xmlHttp = new XMLHttpRequest();

}

}

//发送异步请求

function callServer() {

createXmlHttpRequest();

var str = $(“#t1″).val();

var url = “test1.do”;

// Open a connection to the server

xmlHttp.open(“POST”, url, true);

// Setup a function for the server to run when it’s done

xmlHttp.onreadystatechange = updatePage;

//使用post方法提交是,这句非常重要,否则servlet无法接收参数

xmlHttp.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);

// Send the request

var param = “a=” + str;

xmlHttp.send(param);

}

//回调函数,对页面内容进行更新

function updatePage() {

if (xmlHttp.readyState == 4) {

var response = xmlHttp.responseText;

$(“#t1″).val(response);

$(“#done”).append(response);

}

}

AJAX测试

服务器端的servlet代码:

package andycpp;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class Controller extends HttpServlet {

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String s = req.getParameter(“a”);

resp.setContentType(“text/xml”);

resp.setHeader(“Cache-Control”, “no-cache”);

resp.getWriter().write(s);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值