jsonp回调问题

时间:2011-02-09 06:39:28

标签: jquery ajax json jsonp

我正在尝试以下代码来检索客户端IP,并且它可以正常工作

<script type="text/javascript">  
    function getip(json) {
        var ip = json.ip; // alerts the client ip address
        alert(ip);
    }
</script>
<script type="text/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

但是当我用$.ajax尝试时,它什么也没做......

    $.ajax({
        type: "GET",
        url: 'http://jsonip.appspot.com/?callback=getip',
        dataType: "jsonp",            
        success: function getip(json) {
            alert("sucess");
            var ip = json.ip;
            alert(ip);
        }

    });

});

plz help

3 个答案:

答案 0 :(得分:4)

$.ajax({
    type: "GET",
    url: "http://jsonip.appspot.com/?callback=?",
    //                                        ^
    // ---- note the ? symbol ----------------|
    // jQuery is responsible for replacing this symbol
    // with the name of the auto generated callback fn
    dataType: "jsonp",
    success: function(json) {
        var ip = json.ip;
        alert(ip);
    }
});

jsFiddle demo此处。

答案 1 :(得分:3)

你看到穿过电线的网址了吗?我建议你试试{jsonp:false,jsonpCallback:“callbackName”}。这样可以避免jquery自动添加回调函数。

您是否也将跨域设置为true。?

答案 2 :(得分:0)

您无需在网址中添加任何回调参数。

如果您逐步尝试http://terrasus.com/detail.jsp?articleID=396文章,它将正常工作。如果您生成jsonp响应,则应获取回调值并将其动态设置为您的响应。本文有详细解释。

相关问题