【问题标题】:Perform $.getJSON without using JQuery [duplicate]在不使用 JQuery 的情况下执行 $.getJSON [重复]
【发布时间】:2017-06-20 00:55:15
【问题描述】:

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

【问题讨论】:

  • 你可以使用fetch还是必须使用XHR?
  • 你用谷歌搜索过这个吗?
  • IE 不支持抓取
  • @cruiser,谷歌搜索已经一个小时了
  • youmightnotneedjquery.com/#json。他们可以替代用纯 javascript 编写的 JQuery 方法。

标签: javascript


【解决方案1】:

工作示例:

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>

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

【讨论】:

  • 是的,我刚刚发现我错过了附加IP,检查问题。非常感谢:)
猜你喜欢
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多