按国家/地区代码隐藏 div

Hidden div by Country code

我不是php英雄所以,如果用户不是来自特定国家/地区,我会尝试隐藏一个部分。

所以我这样做了:

$.get("http://ipinfo.io", function (response) {
    $("#country").html(response.country);
}, "jsonp");

<input hidden id="country" type="text" name="country" value="">

这很好用,可以显示国家代码(例如 IT)。 现在我尝试获取此值并插入 IF

$country = $_GET['country'];
$it = "IT";

<?php if ($country != $it): ?>
    Code to hidden here...
<?php endif; ?>

这里有什么问题?

尝试通过 javascript 隐藏,ajax 可以 运行 PHP 脚本并将其带回 DOM,但最好使用 JS如果你不需要后端脚本

$.get("http://ipinfo.io", function (response) {
   var country = $("#country").html(response.country);
   if(country != "IT"){ document.getElementByID("country").display = "none";
}, "jsonp");

<input hidden id="country" type="text" name="country" value="">

改变

$("#country").html(response.country);

$("#country").val(response.country);

因为php $_GET保存值。

我也没有看到这样做的理由:

$it = "IT";
<?php if ($country != $it): ?>

你可以做到

<?php if ($country != "IT"): ?>

最后但同样重要的是,您不应直接访问 $_GET。最好使用函数 filter_input 在你的情况下是 filter_input(INPUT_GET, 'country')

编辑

我不明白隐藏输入有什么用。但是,如果您想根据国家/地区显示或隐藏内容,并且使用 ajax 获取国家/地区,则完全不需要此输入。

而不是制作php条件(<?php if ($country != "IT")...)你可以在js中完成。假设在您的条件中有一个 div 和 class content

解决方案

你的 html 看起来差不多像这样

<div class="content">
    <!-- Your content here -->
</div>

而不是 php 条件。

在 js 中你可以这样做

$.get("http://ipinfo.io", function (response) {
    if (response.country == "IT") {
        $(".content").hide();
    }
}, "jsonp");

那么我们在这里做什么呢?

我们检查国家代码是否等于 "IT"。如果为真,我们将隐藏内容。这与您在 php 中所做的相同(如果国家/地区与 IT 显示内容不同)。

编辑 2

您可以删除

而不是隐藏 div
$(".content").remove();

我使用 ProcessWise cms,它有自己的 API。所以这个答案只适用于 ProcessWise cms。 (最好的一个;))

    <?PHP

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}


$user_ip = getUserIP();

echo "ip: " . $user_ip . "<br />";

$http = new WireHttp();
$url = "http://ipinfo.io/{$user_ip}/country";
$response = $http->get($url, ['country' => '']);


echo "Country: " . $response . "<br />";
echo "Successful response: " . $sanitizer->entities($response) . "<br />";

?>