测试环境:
后台框架:
Spring 3.0.5、Struts 2.3.8
浏览器:IE 8.0.7600.16385、Chrome 28.0.1500.72 m、Safari(win7) 5.1.7(7534.57.2)、Firefox 22.0
使用html采用ajax方式直接调用action存在以下两个问题:
1、除IE外其他浏览器访问后台action都会出现跨域操作错误:
[XMLHttpRequest] cannot load http://localhost:8080/Struts2JsonAjaxTest/jsonAjax.action. Origin null is not allowed by Access-Control-Allow-Origin.
解决方法是:在被调用中的action中声明允许跨域操作,即:
[ServletActionContext].getResponse().addHeader("Access-Control-Allow-Origin", "*") ;
2、使用jQuery封装的$.ajax方法调用后台action时,其他浏览器都可以,IE8访问不到后台(初步查找引起原因是IE8提供的原生json支持,未确认)
解决方法是:使用js原生ajax写法,具体写法详见json2.html
注:另外测试了iPhone 4S、iPad 3、Android手机和pad各一个,全部都能正常运行。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>测试</title>
<script type="text/javascript">
function ajax()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("您的浏览器不支持AJAX!");
return;
}
var url="http://localhost:8080/Struts2JsonAjaxTest/jsonAjax.action"
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
var json = xmlHttp.responseText;
alert(json);
var jsonobj=eval('('+json+')');//单个JSON对象时要加括号,JSON数组就不需要了
alert(jsonobj.result);
}
}
</script>
</head>
<body>
<span>姓名:</span><input id="xm" type="text">
<br/>
<span>身高:</span><input id="sg" type="text">
<br/>
<input type="button" value="提交" id="tj" οnclick="ajax()">
</body>
</html>