ajax查询ip归属地示例

html部分

<!DOCTYPE html>
<html>
<head>
    <title>ip查询</title>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>

    <table>
        <tr>
            <td>查询IP: <input type="text" name="cxip" id="cxip" value=""> <button id="btn">查询</button> </td>
        </tr>
        <tr>
            <td>国家:<span id="Country"></span></td>
        </tr>
        <tr>
            <td>省份:<span id="Province"></span></td>
        </tr>
        <tr>
            <td>城市:<span id="City"></span></td>
        </tr>
        <tr>
            <td>运营商: <span id="Isp"></span>  </td>
        </tr>

    </table>

    <script type="text/javascript">
        $(function(){
            $('#btn').click(function(){
                var cxip = $('input[name=cxip]').val();//使用属性选择器获取查询ip的value值
                if (cxip == '') {
                    alert('请填写IP地址');
                    return;
                }

                $.ajax({
                    url:'index/cxip',
                    data:{cxip:cxip},
                    dataType:'json',
                    type:'post',
                    success:function(res){
                        var json = res;
                        $('#Isp').html(json['result']['Isp']); //给span标签赋值 运营商
                        $('#City').html(json['result']['City']); //给span标签赋值 城市
                        $('#Province').html(json['result']['Province']); //给span标签赋值 省份
                        $('#Country').html(json['result']['Country']); //给span标签赋值 国家

                    }
                })
            })
        })    

    </script>

</body>
</html>

php部分

<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
class Index
{
    public function index()
    {
        
        return view();
    }

    public function cxip(){

        if (request()->isPost()) {
            $data = input();
            $cxip = $data['cxip'];
            $url = "http://apis.juhe.cn/ip/ipNew?ip=$cxip&key=9374fd1994e96feecadc116dcf7aa1b5";
            $list = geturl($url);
            return $list;
        }
       
    }
}

 

posted @ 2021-02-16 22:07  华北业余选手  阅读(91)  评论(0)    收藏  举报