getJSON - 为什么它没有用?

时间:2012-06-26 12:38:59

标签: php javascript jquery json

为什么getJSON方法仅适用于本地文件?如果我想从本地获取json它可以工作,但如果我用http设置url它不起作用。为什么呢?

<!DOCTYPE html>
<html>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <script>
        $.getJSON("http://www.address.com/getTables.php", function (data) {
            $.each(data, function (i, table) {
                $("#tables").append("<p>" + table.id + " " + table.tabname + "</p>");
            });
        });
    </script>

    <body>
        <div id="tables"></div>
    </body>

</html>

返回JSON:

[{ "id":"12", "tabname":"cukry" }, { "id":"11", "tabname":"table" }]

2 个答案:

答案 0 :(得分:3)

听起来你可能正在遇到same-origin policy

答案 1 :(得分:0)

就像马特说的那样,因为same origin policy。尝试使用JSONP。您只需要将回调添加到您的请求网址,如下所示:

$.getJSON("http://www.address.com/getTables.php?jsoncallback=?", function (data) {
        $.each(data, function (i, table) {
            $("#tables").append("<p>" + table.id + " " + table.tabname + "</p>");
        });
    });

详细了解JSONP here