ajax部分
<script type="text/javascript">
function save() {
business = document.getElementById("business").value;
date = document.getElementById("date").value;//获取要向服务器传输的数据
var xmlhttp,post;
//定义XMLHttpRequest对象
if (window.XMLHttpRequest) {// for IE7+,Firefox,Chrome,Opera,Safari
xmlhttp = new XMLHttpRequest();
} else {// for IE6,IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","save.action",true);//设置对应的action
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
post = "data=" + data;
xmlhttp.send(post);
// alert(post);这里一定要注意IE的alert不能写在这里,否则的话得不到返回值;谷歌貌似可以。
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var result = xmlhttp.responseText;//获取返回值
alert(result);
}
};
}
</script>
action部分
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
public class AddRFIDAction extends ActionSupport {
/**
*
*/
PrintWriter out;//创建输出流
HttpServletResponse response;
public String getData() {
return data;
}
public void setDate(String data) {
this.data = data;
}
public void add(){
System.out.println(data);//获取数据
OgnlValueStack stack = (OgnlValueStack) request
.get("struts.valueStack");
response = (HttpServletResponse) stack.getContext().get(
StrutsStatics.HTTP_RESPONSE);
response.setContentType("text/html; charset=UTF-8");
try {
out = response.getWriter();
out.print("传输成功");//通过action向页面传输数据
} catch (Exception e) {
out.print("出现异常");
}
}
}
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
public class AddRFIDAction extends ActionSupport {
/**
*
*/
PrintWriter out;//创建输出流
HttpServletResponse response;
public String getData() {
return data;
}
public void setDate(String data) {
this.data = data;
}
public void add(){
System.out.println(data);//获取数据
OgnlValueStack stack = (OgnlValueStack) request
.get("struts.valueStack");
response = (HttpServletResponse) stack.getContext().get(
StrutsStatics.HTTP_RESPONSE);
response.setContentType("text/html; charset=UTF-8");
try {
out = response.getWriter();
out.print("传输成功");//通过action向页面传输数据
} catch (Exception e) {
out.print("出现异常");
}
}
}
structs的配置
<action name="save" class="com.csdn.action.ajax
"
method="save">
</action><!--这里千万不要配置@R_949_404@面,否则将会出现在ajax得到的返回值中-->
原文链接:https://www.f2er.com/ajax/165085.html