struts2中Ajax的操作实现及其核心对象XMLHttpRequest对象的使用
来源:互联网 发布:淘宝屏蔽黑名单在哪 编辑:程序博客网 时间:2024/05/29 21:31
在一个网页文件中可以采用如下的XMLHttpRequest对象的写法实现Ajax的异步操作
function getValueFromServer(){var xmlHttpRequest = null; if(window.ActiveXObject){//如果是通过microsoft的activeXObject实现的xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){//如果是通过Firefox和Chrome实现的。xmlHttpRequest = new XMLHttpRequest();}if(null != xmlHttpRequest){//方法里的true代表是异步的方式,而false是同步的方式 发送GET请求, "MyServlet"表示的是请求的相对urlxmlHttpRequest.open("GET","addAction" + "?value1=" + value1 + "&value2=" + value2,true);xmlHttpRequest.onreadystatechange = ajaxCallBack;/*如果发送的请求是GET类型的,参数赋值null如果有请求参数在xmlHttpRequest.open("GET","MyServlet",true)中的"MyServlet"中添加,形式如"MyServlet?username=hello&password=world"如果是POST的类型的参数以名值对的形式卸载send()方法里面*/xmlHttpRequest.send(null);}function ajaxCallBack(){if(xmlHttpRequest.readyState == 4){//http请求是正确的(200)if(xmlHttpRequest.status == 200){//请求的数据格式为普通文本。var responseText = xmlHttpRequest.responseText;document.getElementById("div1").innerHTML = responseText;}}}}至于服务器端可以采取如下的代码去配合(如果使用的是struts2的话)
ServletResponse httpServletResponse = ServletActionContext.getResponse();PrintWriter printWriter = null ;try{ printWriter = httpServletResponse.getWriter();}catch (IOException e){e.printStackTrace();}
可以通过PrintWriter类的对象产生一个信号,回传给客户端。在之前的javascript的脚本段中定义的那个回调函数里有一个xmlHttpRequest.responseText; 标示回传的是一个普通的文本的格式而不是一个xml格式也不是一个json数据格式的。并且里面放的值就是PrintWriter对象所返回的数据。
function ajaxCallBack()
{
if(xmlHttpRequest.readyState == 4)
{
//http请求是正确的(200)
if(xmlHttpRequest.status == 200)
{
//请求的数据格式为普通文本。
var responseText = xmlHttpRequest.responseText;
document.getElementById("div1").innerHTML = responseText;
}
}
}
如果是servlet的话直接就是
PrintWriter printWriter = resp.getWriter(); //res为HttpServletRequest对象
0 0
- struts2中Ajax的操作实现及其核心对象XMLHttpRequest对象的使用
- AJAX的核心XMLHttpRequest对象
- Ajax的核心对象XMLHttpRequest
- AJAX的核心对象XMLHttpRequest
- Ajax中XMLHttpRequest对象的使用
- 为何XMLHttpRequest对象是AJAX的核心
- Ajax的核心——XMLHttpRequest 对象
- XMLHttpRequest对象是AJAX的核心
- ajax的核心javascript对象XMLHttpRequest创建
- 【AJAX】XMLHttpRequest对象的使用
- 【Ajax 2】封装Ajax的核心对象:XMLHttpRequest对象
- Ajax-核心对象--XMLHttpRequest 对象使用详解
- AJAX核心对象-- XMLHttpRequest 对象使用详解
- Ajax核心对象-- XMLHttpRequest 对象使用详解
- AJAX使用 以及 AJAX核心:XMLHttpRequest对象
- Ajax核心对象-- XMLHttpRequest
- AJAX核心XMLHttpRequest对象
- AJAX核心对象XMLHttpRequest
- 由crossdomain.xml安全策略文件引发的一些列安全问题
- 云计算里AWS和Azure的探究(6) - Amazon Simple Storage Service 和 Microsoft Azure Blob Storage
- Android Toast 五中特效
- 关于JS加载顺序
- Java虚拟机OutOfMemoryError 异常详解及解决方法(3)
- struts2中Ajax的操作实现及其核心对象XMLHttpRequest对象的使用
- win32 创建控件
- 微信平台开发API指南地址
- Caffe运行googlenet模型 matlab接口错误
- GNU Autotools的使用方法
- jQuery UI draggable+droppable+resizable+selectable+sortable
- 杭电ACM 2003: 求绝对值
- leetcode 18 4Sum
- C/C++产生随机数