【问题标题】:Is it possible to run code if visitor IP is from a specific country如果访问者 IP 来自特定国家,是否可以运行代码
【发布时间】:2023-04-04 09:18:01
【问题描述】:

我只想在访问者来自特定国家/地区时运行此代码

window.onload=function(){ document.getElementById("buy").click(); };

我试过了,但没有用:

 var requestUrl = "http://ip-api.com/json";
var xhr = new XMLHttpRequest();
xhr.open('POST', requestUrl, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
    var json = JSON.parse(xhr.responseText)
    if(json.country == 'France'){
        document.getElementById("buy").click(); 
    };
};
xhr.send(null);

【问题讨论】:

  • 您将如何确定访问者所在的国家/地区?
  • 这就是我所要求的,比如使用像这样的 json 链接:ip-api.com/json 然后设置规则,比如来自“德国”的访问者是否运行脚本,如果不只是忽略它
  • 你问的是不同的东西,恕我直言。
  • @charlietfl 我没有得到答案兄弟,它是这样的,但这个不起作用:function Get(ip-api.com/json){ xhr.open('POST', GET, true) ; xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onload = function () { var json = JSON.parse(xhr.responseText); if (json.country == 'Germany') { document.getElementById("buy").click(); } }; xhr.send(null);
  • 嗨 Aymn,欢迎来到 StackOverflow。这个问题看起来可能以前被问过。看看这是否回答了您的问题:stackoverflow.com/questions/48278024/…

标签: javascript jquery html


【解决方案1】:

以下是使用相同 API 的简单方法:

fetch('http://ip-api.com/json').then(response => {
    return response.json();
}).then(data => {
    if (data.country == "France") {
        document.getElementById("buy").click();
    }
});

或者如果你更喜欢 jQuery:

$.getJSON("http://ip-api.com/json", function(data) {
    if (data.country == "France") {
        $("#buy").click();
    })
});

【讨论】:

  • 谢谢你,我试过了,但当页面加载法国 IP 时仍然无法正常工作
  • 我不知道为什么没有window.onload=function(){
  • 任何解决方案兄弟
猜你喜欢
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
相关资源
最近更新 更多