jsonp callback problem

邮差的信 提交于 2020-01-13 05:40:09

问题


i'm trying the following code to retrieve the client ip, and it works fine

<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>

but when i try it with $.ajax it does nothing...

    $.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


回答1:


$.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 here.




回答2:


Did you see the url that is passed across the wire? I suggest you try { jsonp: false, jsonpCallback: "callbackName" }. This will avoid jquery from adding the callback function automatically.

Also did you set cross domain to true.?




回答3:


You dont need to add any callback parameter in url.

If you try http://terrasus.com/detail.jsp?articleID=396 article step by step it will work fine. if you produce jsonp response you should get the callback value and set it to your response dynamically. This article has a detail explanation.



来源:https://stackoverflow.com/questions/4942004/jsonp-callback-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!