如何从GET jsonp请求的回调中捕获数据?

时间:2019-04-22 19:17:51

标签: ajax request jsonp

我正在尝试处理jsonp请求的回调,但是回调函数未运行。

$(document).ready(function() {

    $.ajax({
        url: 'https://storage-testnet.shiftproject.com/peers?callback=?',
        type: "GET",
        dataType: 'jsonp',
        jsonpCallback: 'peersData',
        complete: peersData
    });

    var peersData = function (data) {
        if(!data){
            console.log("Error, can't retrieve data");   
        } else {
            console.log(data)
        }
    } 
}

有什么错误吗?

2 个答案:

答案 0 :(得分:0)

您的数据没有包装在便笺簿中。以下

<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
    //credit https://www.sitepoint.com/jsonp-examples/
    function jsonCallback(json) {
        console.log(json);
    }
    $.ajax({
        url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
        dataType: "jsonp"
    });
</script>

答案 1 :(得分:0)

https://jsfiddle.net/kblau237/pmw0yah9/5/

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Tut156</title>
    <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#theButton").click(function () {
                //moved your stuff inside a button click
                $.ajax({
                    //question mark for callback will cause jquery to generate a random callback
                    //I am taking out the callback
                    url: 'https://storage-testnet.shiftproject.com/peers',
                    type: "GET",
                    dataType: 'json',
                    success: function (data) {
                        alert(JSON.stringify(data));
                    }
                });
            })
        })
    </script>
</head>
<body>
    <div>
        <input type="button" id="theButton" value="Go" />
    </div>
</body>
</html>