天天看点

js跨域 ajax跨域问题解决

想要通过ajax获取服务器内容,如果在本地获取,则会出现跨域问题:

  1. 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  
  2. Resource interpreted as Script but transferred with MIME type text/html:  

想要解决,则不能通过json的方式:

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'

继续阅读