【问题标题】:How to catch a data from callback of GET jsonp request?如何从 GET jsonp 请求的回调中捕获数据?
【发布时间】:2019-09-11 23:16:10
【问题描述】:

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


    【解决方案1】:

    您的数据未包含在 pad 中,例如。以下

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

    【讨论】:

    • 谢谢,我认为即使服务器没有 CORS 策略,我也可以使用 jsonp 请求数据。
    【解决方案2】:

    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>
    

    【讨论】:

      猜你喜欢
      • 2013-12-07
      • 1970-01-01
      • 2017-12-30
      • 2017-11-19
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2017-09-28
      • 2013-11-01
      相关资源
      最近更新 更多