不使用JQuery

时间:2017-02-02 19:39:22

标签: javascript

如何仅使用javascript获取国家/地区代码,我不允许使用jQuery。

我见过像http://ipinfo.io这样的网站,但是所有的例子都使用了JQuery getJson,我可以实现相同的方法:

var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
    country_code = data.country;
    alert(country_code);
});

我尝试了以下操作,但它返回了一个页面:

var request = new XMLHttpRequest();

request.onload = function(elements) { console.log(elements); };
request.open("get", "http://ipinfo.io", true);
request.send();

1 个答案:

答案 0 :(得分:2)

工作示例:



var someIp = '8.8.8.8';
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == XMLHttpRequest.DONE) {
    if (xmlhttp.status == 200) {
      document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
    else if (xmlhttp.status == 400) {
      alert('There was an error 400');
    }
    else {
      alert('something else other than 200 was returned');
    }
  }
};

xmlhttp.open("GET", "//ipinfo.io/"+someIp+"/json", true);
xmlhttp.send();

<div id="myDiv">
  pending
</div>
&#13;
&#13;
&#13;

仅当附加了正确的请求JSON的标头时, ipinfo.io 服务才会返回JSON格式。但是,也可以使用/json直接在请求网址中轻松指定。