krzakov
krzakov

Reputation: 4111

AJAX & jQuery $.getJSON(...) throws XMLHttpRequest

This could be another "I'm dinosaur" question, but I'm just starting with front-end stuff.

So I built application which returns me JSON via URL:

http://localhost:8080/json

and this returns:

{"id":41,"content":"Hello, World!"}

dev tools:

Remote Address:[::1]:8080
Request URL:http://localhost:8080/json
Request Method:GET
Status Code:200 OK

Well I've managed to create "web application" with following code:

<!DOCTYPE html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
</body>
<script>
    $.getJSON("http://localhost:8080/json", function(response) {
        alert(response);
    });
</script>
</html>

When i launch it I can see on a console:

XMLHttpRequest cannot load http://localhost:8080/json. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access.

Why on earth this thing don't want to cooperate. What m I missing here?

Upvotes: 0

Views: 292

Answers (1)

overflowed
overflowed

Reputation: 1838

When your "Webapplication" is not hosted under Access-Control-Allow-Origin than the webserver on localhost:8080 needs to allow you to do XMLHttpRequest. This must be done by the HTTP Header Access-Control-Allow-Origin (which can also contain * for every site or an url of your "Webapplication")

Upvotes: 1

Related Questions