1、前端ajax写法,解释:CK方法就是通过ajax进行跨域访问,通过jsonp的形式。注意,callback方法不能丢,返回的值都在callback方法里处理。
function ck(){
$.ajax({
url:'http://127.0.0.1:8080/rhzf/indexController.do?getXf',
type:'get',
dataType:'jsonp',
async:true,
jsonp:'callback',
cache:'true',
jsonpCallback:'callback',
success:function(data){
},
error:function(e){
alert("chucuo");
console.log(e);
}
});
}
function callback(data){
alert('进来了。。。。。');
console.log(data);
$("#d").val(data);
}
2、java后端:
1》低版本springMVC:系统里写上这个配置类,然后再web.xml中配置一下。
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,PUT,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Accept,Origin,X-Requested-With,Content-Type,X-Auth-Token");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.jeecgframework.core.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
2》高版本springMVC(4.2以上,包括4.2)的写法:
在Controller上使用@CrossOrigin
注解就OK了。
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
3、controller中的写法,统一的,不管是低版本高版本都一样,注意接收callback参数,不然浏览器控制台会报警,导致拿不到数据。最终返回的数据也需要按照下述格式进行包括。
@ResponseBody
@RequestMapping(params = "getXf")
public String getXf(@RequestParam("callback") String callback){
List<TXfitemEntity> listbySql = tXfitemServiceI.getList(TXfitemEntity.class);
return callback+"("+JSONObject.toJSONString(listbySql)+")";
}