John Smith
John Smith

Reputation: 6259

Get json from another site

Its the first time i have to deal with json in jquery. And im facing some problems, when i open:

http://localhost:3000/calendar/termine/24-11-2013

In my browser i get:

[{"id":73539,"name":"Anneliese","input":"18-40"},{"id":73537,"name":"Appolonia","input":"14-20"}]

So when i simply copy it and at it as a variable my code works:

 var array = [{"id":73539,"name":"Anneliese","input":"18-40"},{"id":73537,"name":"Appolonia","input":"14-20"}]

Then i tried the same with jquery:

var array = $.getJSON("/calendar/termine/24-10-2013");

This somehow wont work! What did i wrong?

When i open the page ..termine/24-10-2013 the output looks like this so now im not 100 percent sure if its real json:

<html>

    <head> … </head>
    <body>
        <pre>

            [{"id":null,"name":"sara","input":"11"},…

        </pre>
    </body>

</html>

Upvotes: 0

Views: 147

Answers (3)

uzaky
uzaky

Reputation: 39

You have to get the json data then parsing it then looping and fetching it using each like that:-

$('document').ready(function(){
    jQuery.get("your/url/that/get/json/",function(data) {
     data = jQuery.parseJSON(data);
     jQuery.each(data, function(key, value) {                   
    jQuery('#dataContainer').append(value.id+"<br>"+value.name);
    });
});

supposing you have any html area <div id="dataContainer"></div>

Hope this helpful.`

Upvotes: 0

You have to wait for the response, then set the variable.

var array;

$.getJSON("/calendar/termine/24-10-2013", function(data){
     array = data;
});

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150040

As explained in the $.getJSON() method documentation, it doesn't return the result, it returns a jqXHR object. You need to provide a callback to receive the results, and because the callback is called asynchronously you need to work with the result there:

$.getJSON("/calendar/termine/24-10-2013", function(array) {
     // do something with array here
});

"from another site"

If you really are trying to retrieve data from a different domain then you will have a problem due to the same origin policy, but in your example the URL you are using seems to be a path on the same domain as the page. If it is a different domain you can use JSONP instead if the other domain supports it - of course if you control that page you can implement JSONP as an option yourself.

Upvotes: 2

Related Questions