1 JSONP
2 CORS
3 服务器代理
返回的结果是JSON对象,则直接使用回调方法function(data){}对data进行处理。
如果返回的是js代码,采用script加载。可以采用jQuery加以简化:
$.ajax({
url:url,
dataType:"script",
cache: true/false, //是否进行数据缓存
success:function(data){
});
}});
浏览器缓存,响应端可以通过设置header决定数据是否缓存。
Response Headers:
Cache-Control:no-cache
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:171
Content-Type:application/x-javascript; charset=GBK
如果响应端支持缓存,客户端也可以设置为不支持缓存。
jQuery采用添加一个时间戳,修改url请求。
jquery代码如下:
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
使用angularjs写了一个跨域请求新浪股票接口的demo,代码路径:
http://img.kuitao8.com/uploads/2015/0203/20150203012905375.zip
转载请注明:谷谷点程序 » jquery 跨域请求和浏览器缓存