Hbuilder编辑App时,ajax跨域访问失败问题

今天试着用Hbuilder写app的前段显示页面,在第一步时就被打住了,ajax异步调用服务器的登录接口时,报错,

显示这样的错误

XMLHttpRequest cannot loadhttp://www.baidu.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

这个百度的网址是我自己试着玩的,然后我就开始寻找解决的办法。

网上给出的办法好像有两种,我给出我选用的这种,并且亲测成功。

document.getElementById("submitBut").addEventListener('tap',function ajaxPost(){
	mui.ajax('http://localhost:8080/demo01/user_service', {
	data: {

	},
	dataType: 'json', //服务器返回json格式数据
	type: 'post', //HTTP请求类型
	timeout: 10000, //超时时间设置为10秒;
	success: function(data) {	
		mui.openWindow('index.html', 'id', {})

	},
	error: function(xhr, type, errorThrown) {
		
	}
});
});

这个是我App端js的访问代码,如果访问成功就跳转到主界面。

服务器端的话,我是用的struts2,写了一个void action方法来接收ajax的访问,并且返回json格式的数据。

action中的代码如下:

  

HttpServletResponse response = ServletActionContext.getResponse();
/**
*需要添加下面三行header头
*/
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE"); //支持的http 动作 response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type"); //响应头 请按照自己需求添加。

Map<String,Object> result=new HashMap<String,Object>(); ServletOutputStream out = response.getOutputStream(); result.put("result","success"); result.put("message","message"); result.put("description","description"); JSONObject json = new JSONObject(result); out.println(json.toString());

然后就可以ajax跨域访问了。

网上还有一种方法是 把ajax中的数据格式从json改成jsonp,我没测试;

还有一种说的是 把mui.js中的代码注释掉一行,这个我测试失败。

还有一种说法,测试项目的时候,不要把地址写成localhost或者127.0.0.1,win+R,输入cmd,输入ipconfig,然后查看自己的ipv4地址,没有测试,大家想要测试的可以试一试,玩意对了呢?

猜你喜欢

转载自www.cnblogs.com/sixgodbiao/p/10492217.html
今日推荐