除了CORS实现跨域,也可以利用JSONP,不过JSONP只能实现get请求,并且受URL地址长度的限制。
首先打开腾讯天气的网站,打开network,找到类型为script报文(双击查看哪个是请求天气的,记得下载jsonp插件),分析请求参数
https://wis.qq.com/weather/common?source=pc&weather_type=observe%7Cforecast_1h%7Cforecast_24h%7Cindex%7Calarm%7Climit%7Ctips%7Crise&province=%E5%B9%BF%E4%B8%9C%E7%9C%81&city=%E6%B7%B1%E5%9C%B3%E5%B8%82&county=&callback=jQuery111303792346658619239_1622463631895&_=1622463631897
callback后面为回调函数的名称直接不看,乱码是中文,可以猜出是你所在的省份和城市
https://wis.qq.com/weather/common?source=pc&weather_type=observe%7Cforecast_1h%7Cforecast_24h%7Cindex%7Calarm%7Climit%7Ctips%7Crise
后面根据JSONP的数据我选了forecast_1h这个数据
下面上代码
<button>点击获取天气信息</button>```
```javascript
let obj = {
url: 'https://wis.qq.com/weather/common',
data:{
source:'pc',
weather_type:'forecast_1h',
province:"广东省",
city:"深圳市"
},
success:res => {
console.log(res);
}
}
let btn = document.querySelector("button");
btn.addEventListener('click',function(){
myjsonp(obj)
})
function myjsonp(options){
const {data} = options
let script = document.createElement("script");
let urlparam = '';
for(let key in data){
urlparam = urlparam+key+'='+data[key]+"&"
}
fn = 'jsonp'+Math.random().toString().substr(3,10)
// substr(2,10) 提取指定数目的字符串,从2开始提取10个字符
// substring(2,10)提取指定下标之间的字符串从2到10,不能接受负数
// slice() 与 substr() 有所不同,因为它用两个字符的位置来指定子串,
// 而 substr() 则用字符位置和长度来指定子串。
window[fn] = options.success
script.src = options.url+"?"+urlparam+'callback='+fn;
document.body.appendChild(script)
script.onload = function(){
document.body.removeChild(script)
}
}