不使用jQuery执行$.getJSON

13 浏览
0 Comments

不使用jQuery执行$.getJSON

这个问题已经有答案了:

如何在没有jQuery的情况下进行AJAX调用?

如何仅使用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();

admin 更改状态以发布 2023年5月24日
0
0 Comments

工作示例:

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();


  pending

当正确的请求JSON头附加时,ipinfo.io服务仅返回JSON格式。但也可以通过在请求URL中直接指定/json来轻松指定。

0