ajax接口調用過程當中常常會遇到json跨域問題,解決方法以下:php
[****jsonp方式暫不使用****]java
1.使用getScript方式解決web
$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js',function(){ajax
console.log(remote_ip_info.city);spring
});json
2.從服務器端解決(新增自定義filter)跨域
<1> CORSFilter.java服務器
public class CORSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* Access-Control-Allow-Headers: Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport, * Access-Control-Allow-Methods: POST, GET, OPTIONS , PUT Access-Control-Allow-Origin: * Access-Control-Request-Headers: Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport,* */ ((HttpServletResponse)response).setHeader("Access-Control-Allow-Headers", "Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport, *"); // ((HttpServletResponse)response).setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS , PUT"); ((HttpServletResponse)response).setHeader("Access-Control-Allow-Origin", "*"); // ((HttpServletResponse)response).setHeader("Access-Control-Request-Headers", "Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, X-Atmosphere-Transport,*"); // ((HttpServletResponse)response).setContentType("application/json"); // ((HttpServletResponse)response).setHeader("Connection", "keep-alive"); chain.doFilter(request, response); } @Override public void destroy() { } }
<2>web.xml新增過濾器配置app
<filter> <filter-name>CORSFilter</filter-name> <filter-class>com.chuyan.common.filter.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<3>spring容器加載過濾器 applicationContext.xml (可選,須要注入屬性的時候配置。這裏能夠不用配置)ide
<bean id="CORSFilter" class="com.chuyan.common.filter.CORSFilter"/>