无法从Web URL获取JSON对象

时间:2016-05-29 21:27:41

标签: javascript jquery json ajax jsonp

我正在尝试从我的javascript应用程序中的this第三方服务访问JSON对象。

但是,因为我之前收到了同源策略错误,所以我分别尝试使用JSONP和jQuery和AJAX,如下所示。

使用JSONP

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    function foo(data)
    {
        // do stuff with JSON
        console.log(data);
    }

    var script = document.createElement('script');
    script.src = 'https://matchstat.com/tennis/match-stats/m/8348298?callback=foo'

    document.body.appendChild(script);
    // or document.head.appendChild(script) in modern browsers
</script>
</body>
</html>

使用jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script>
    $.getJSON("https://matchstat.com/tennis/match-stats/m/8348298?callback=?", function(data) {
        console.log(data);

        // Get the element with id summary and set the inner text to the result.
        $('#summary').text(data.result);
    });
</script>
</body>
</html>

使用AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script>
    CallURL();

    function CallURL(){
        $.ajax({
            url: 'https://matchstat.com/tennis/match-stats/m/8348298',
            type: "GET",
            dataType: "jsonp",
            async:false,
            success: function (msg) {
                JsonpCallback(msg);
            },
            error: function () {
                ErrorFunction();
            }

        });

    }

    function JsonpCallback(json)
    {
        console.log("came inside JsonpCallback ...");
        document.getElementById('summary').innerHtml=json.result;
    }

    function ErrorFunction()
    {
        console.log("came inside the ErrorFunction() ...");
    }
</script>
</body>
</html>

但是,我还无法访问JSON对象。

0 个答案:

没有答案