通过js获取本地IP地址

最近在做pc项目,需要根据用户的IP地址定位城市。IP地址需要通过js获取:
网上有很多查询接口可以获取到IP,我这里用的是搜狐的:
http://pv.sohu.com/cityjson?ie=utf-8

  1. 在浏览器中,直接输入这个地址,就可以获取到ip信息:
    [图片上传中...(1.png-4dc2ae-1536549955072-0)]
  1. 在js文件中,实现如下:
jQuery.getScript(
    "http://pv.sohu.com/cityjson?ie=utf-8",function(data){  
    //localIP = returnCitySN["cip"];    
    console.log(returnCitySN);
        });

3.关于jQuery.getScript()
官方api说明:Load a JavaScript file from the server using a GET HTTP request, then execute it.(通过get请求,加载其他JavaScript文件并运行)
4.问题
从网上看到,jQuery.getScript() 相当于

$.ajax({
    url: url,
    dataType: "script",
    success: success
});

但是为什么我自己在写的时候,jQuery.getScript()可以生效,但是$.ajax()写法无法生效呢?


(更新:以下的写法可以生效,之前测试没生效的原因是格式不正确)

$.ajax({
url: 'http://pv.sohu.com/cityjson?ie=utf-8',
dataType: "script",
success: function(){
         console.log(returnCitySN);
        }
});

你可能感兴趣的:(通过js获取本地IP地址)