jQuery值未按预期从ipinfo分配

jQuery value not getting assigned from ipinfo when expected

本文关键字:ipinfo 分配 jQuery      更新时间:2023-09-26

我使用的是:

//function to obtain current location, this is used to display relevant contact information
    $.get("http://ipinfo.io", function(response){
        $("#address").html(response.region);//http://jsfiddle.net/zK5FN/2/
        $("input[id=address]").val(response.region);
    }, "jsonp");

以获取我的联系人页面的当前位置。目的是我可以使用if地址==来显示各种联系电话等

此函数用于更新隐藏字段的值。我已经检查了调试器,它运行良好。

然后我想得到这个值,这样我就可以玩了,但它总是空白或空的。

我有

$(document).ready(function(){
            var testLoc = $('#address').val();
            if(testLoc == ""){
                alert("NOES!!!");
            }
        });

我目前已经将其放置在头部的同一脚本块中,以查看结果是否不同,同样,它始终为空,并且始终返回NOES警报。

我想,通过等待文档加载,我可以确定这些值会被分配/设置。

有人能提出解决方案吗?我确信有一个简单的解决方案,它正在杀死我

编辑:HTML

<input type="hidden" name="address" id="address"/>

使用解决方案编辑:

    <script>
    $(function() {
        $.ajax({url:"http://ipinfo.io",dataType:'jsonp'})
            .success(function(response){
                $("#address").val(response.region);
                $("input[id=address]").val(response.region);

                var testLoc = $('#address').val();
                if(testLoc == ""){
                    alert("NOES!!!");
                }else{
                    alert("jQuery can suck my...")
                }
            });
    });
</script>

我建议将$.get请求放入document.ready函数中。

请注意,一旦DOM准备好,就会调用ready函数,因此即使AJAX在此之前返回,您正在填充值的元素也可能还没有准备好。

$(function() { // this is shorthand for $(document).ready(
    $.get({url"http://ipinfo.io",dataType:'jsonp'})
    succsss(function(response){
        // do something with response
    });
});

Fiddle:http://jsfiddle.net/v6DBB/

在get()返回后才能检查地址:

$(document).ready(function () {
    $.get("http://ipinfo.io", function (response) {
        $("#address").html(response.region); //http://jsfiddle.net/zK5FN/2/
        $("input[id=address]").val(response.region);
        var testLoc = $('#address').val();
        if (testLoc == "") {
            alert("NOES!!!");
        }
    }, "jsonp");
});

也就是说,当我运行这个时,response.region为null,所以我仍然得到警报。