jsonp跨域的本质实际就是动态的创建了script标签,script的src属性就是其他服务器地址,get情况下是在url后传参,记得还有个回调函数
<h1>天气信息</h1> <input type="text" id="text" placeholder="请输入城市名字"> <input type="button" value="查询" id="btn"> <script> var textVal = document.querySelector('#text').value var btn = document.querySelector('#btn') btn.onclick = function(){ var script = document.createElement('script') script.src = './data/php?city=' + textVal + '&cb=callback' window['callback'] = function(data){ console.log(data) } var head = document.querySelector('head') head.appendChild(script) } </script>
<?php $cb = $GET["callback"]; $cityName = $GET["city"]; if($cityName == "suqian"){ echo $cb."('宿迁的天气真不错')"; }else{ echo $cb."('没有查到当地信息')"; } ?>