pkrr
pkrr

Reputation: 1

getJSON - why it didnt work?

Why getJSON method works only with local files? If I want to take json from local it works, but if I set url with http it doesnt work. why?

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

Returned JSON:

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

Upvotes: 0

Views: 229

Answers (2)

Rafael Sedrakyan
Rafael Sedrakyan

Reputation: 2629

Like Matt said it`s because of the same origin policy. Try using JSONP. You just need to add callback to your request URL like this:

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

See more about JSONP here

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

It sounds like you're probably running into the same-origin policy.

Upvotes: 3

Related Questions