function constUpdate()
{
$.ajax({
url: "https://pv.sohu.com/cityjson?ie=utf-8",
type: 'get',
dataType: 'json',
crossDomain: true,
success:function (data) {
alert(data)
},
error:function (dat){
alert(returnCitySN["cip"]);
}
});
}
在操作的时候打算使用单独的js文件封装,这样在每一个jsp界面只需要调用就可以获得用户的IP地址了,但是这样的写法明显是有问题的。但是如果直接尝试使用
```javascript
document.write("<script src=\"https://pv.sohu.com/cityjson?ie=utf-8\"></script>");
这样的话,就会出现这种提示
将获取ip的方法封装在一个getIpInfo.js文件中
function constUpdate() {
return new Promise((resolve, reject) => {
$.ajax({
url: "https://pv.sohu.com/cityjson?ie=utf-8",
type: "get",
dataType: "json",
crossDomain: true,
success: function (data) {
resolve(data);
window.sessionStorage.setItem("ipInfo", data);
},
error: function (dat) {
reject(returnCitySN["cip"]);
},
});
});
}
async function getIpInfo() {
let ipInfo = window.sessionStorage.getItem("ipInfo");
if (ipInfo) return ipInfo;
ipInfo = await constUpdate();
return ipInfo;
}
使用方式
<script src="./getIpInfo.js"></script>
<script>
// 使用
const ipInfo = getIpInfo();
</script>
单独的js文件写获取IP的方法
jsp页面引入这个js调用
有什么问题?
把你的这个 constUpdate 直接封装成一个 js单元,在页面里面引用就可以了,都 能调用 constUpdate 函数了
constupdate单独一个js文件这样就能共用了
document.write("<script async src=\"https://pv.sohu.com/cityjson?ie=utf-8\"></script>");
async 异步加载文件,注意前提 不依赖其他文件
1.方法一 ,将获取ip的方法写成一个函数,挂载到window上
// 这是挂载
window.GET_IP=function(){
return {
ip:'我是ip',
}
}
// 这是应用
window.GET_IP().ip
2.常规导入