想要通过ajax获取服务器内容,如果在本地获取,则会出现跨域问题:
- XMLHttpRequest cannot load http://v.xxx.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. test.html:1
- Resource interpreted as Script but transferred with MIME type text/html:
jsonp轻松解决:
$.ajax({
type: 'get',
url: 'http://v.juhe.cn/weather/index',
data: {format:2,cityname:'北京',key:'XXX'},
dataType: 'jsonp',
crossDomain: true,
success: function(res){
console.log(res);
}
});
关键是 dataType:'jsonp'