关于mui框架跨域问题,很多人说在浏览器上,无法调用后台,在真机上调试可以,但是,我用Android、IOS都试过了,无法调用本地后台接口。我不知道是不是我后台接口配置的问题,但是我自己额外用sublime text3 在本地建一个网页,是可以调用后台的,且url没有变过,都是"http://localhost:8080/VankeCCFinal/getJson",我后台用的是java,我在后台中也写了
resp.setHeader("Access-Control-Allow-Origin","*");
resp.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS");
resp.setHeader("Access-Control-Allow-Headers","content-type,Authorization,Accept,X-Requested-With");
我现在也找不到原因,为何mui中,真机调试也调用不了后台接口。
这是我简单做的一个测试能否调用后台接口的例子,找不到调用不了接口的原因:
前台代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<script src="js/mui.min.js"></script>
<link href="//ask.dcloud.net.cn/css/mui.min.css" rel="stylesheet"/>
<script src="js/mui.jsonp.js"></script>
<script type="text/javascript" charset="utf-8">
mui.init();
</script>
</head>
<body>
<p id="demo"></p>
<script>
mui.plusReady(function(){
console.log("1");
mui.getJSON("http://localhost:8080/VankeCCFinal/getJson",{},function(resp){
alert("1");
});
});
</script>
</body>
</html>
后台代码:
package com.vankecc.bao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class JsonServlet extends HttpServlet{
public static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Access-Control-Allow-Origin","*");
resp.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS");
resp.setHeader("Access-Control-Allow-Headers","content-type,Authorization,Accept,X-Requested-With");
UserDao dao = new UserDaoImpl();
List<User> list = dao.query();
//将数据封装到用户总计类
NewTotal nt = new NewTotal(list.size(),list);
//调用GSON jar工具包封装好的toJSON方法,可直接生成JSON字符串
Gson gson = new Gson();
String json = gson.toJson(nt);
//输出到界面
System.out.println(json);
resp.setContentType("text/plain");
resp.setCharacterEncoding("gb2312");
PrintWriter out = new PrintWriter(resp.getOutputStream());
out.print(json);
out.flush();
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
LaughingSong (作者)
@responsebody 是SpringMVC框架是吗, 但是我这里java后台没有用SpringMVC框架额,
2018-03-28 00:16
无言名
你试试行不行,反正后台返回的数据必须是json格式的数据
2018-03-28 09:34