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

问题描述 投票:0回答:2

我正在尝试处理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)
        }
    } 
}

有错吗?

ajax request jsonp
2个回答
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>

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>
© www.soinside.com 2019 - 2024. All rights reserved.