问题描述:
1. 使用ajax接收后台传递过来的转化为string类型的json数据时进入error函数,
2. 且alert()方法打印出在error中获取到的responseText内容为空,
3. 使用chrome浏览器,在console页面看到报错:No 'Access-Control-Allow-Origin' header is present on the requested
分析原因:http请求跨域被拦截
解决方法:
在后台response中追加设置:response.setHeader("Access-Control-Allow-Origin", "*");
结果:可正常获取数据
备注:
Access-Control-Allow-Origin:* 表示允许任何域名跨域访问
如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名
例如在这里我的tomcat运行在ip=192.168.1.100的本地,所以可以设置:response.setHeader("Access-Control-Allow-Origin", "http://192.168.1.100:8080");
如设置*,请注意跨域风险
例如:header('Access-Control-Allow-Origin:http://www.client.com');
附上部分代码:
后台:
public class GetInforAction extends ActionSupport {
public String selectRecord(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json; charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "*");
Map<String, Map> jsonMap = new HashMap<String, Map>();
jsonMap.put("infor", "信息内容");
JSONArray returnJson=JSONArray.fromObject(jsonMap);
try {
PrintWriter out = response.getWriter();
System.out.println(returnJson.toString());
out.print(returnJson.toString());
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; //使用了struts2,所以用return null阻止跳转
}
前端部分:
<body>
<div>
<input type="text" class="companyName" name="companyName" id="companyName" />
<button class="button" οnclick="getInfor()">submit</button>
</div>
</body>
<script type="text/javascript">
function getInfor(){
var companyName="companyName="+$("#companyName").val(); //data传递过去数据,java是通过=前的名字来获取的
$.ajax({
type:"post",
url:"http://127.0.0.1:8080/resposneTable/getInfor" //getInfor是struts.xml中设置的action name
data:companyName, //把text中内容传递到后台
dataType:"json",
success:function(data){
alert("*********");
},
error:function(msg){
alert(JSON.stringify(msg));
}
});
}
</script>