在网站开发过程中,遇到后台传入了一些JSON数据,其中数据中有IP,但是前端页面需要显示这个IP的位置。话不多说,直接上代码!
- 以下代码是有问题的代码,会出现(No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.)这个问题,百度了一下,这个问题是跨域问题。但是查本机的IP,是没有问题的。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>IP定位</title>
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
var ip="ip=113.2.1.3";
$.ajax({
type: "get",
async: false,
url: "https://api.map.baidu.com/location/ip?ak=您的AK&coor=bd09ll&"+ip,
dataType: "jsonp",
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
jsonpCallback:"address",//自定义的jsonp回调函数名称
success: function(json){
alert('您查询到的地址: ' + json.content.address );
},
error: function(){
alert('没有查询到!');
}
});
});
</script>
</head>
<body>
</body>
</html>
以上就是我分享的代码了。 推荐一下,我的群:789826996
其中有参考了 https://www.cnblogs.com/ylyw/p/7825345.html 这位作者的代码。