How to get a json on an external server with Javascript?

0

Hello everyone, I need to get a json with javascript on an external server! Does anyone know how to do this?

    
asked by anonymous 26.03.2014 / 15:47

2 answers

2

What you need to do is make an AJAX call ...

Example

var endereco = 'http://echo.jsontest.com/key/value/one/two';
$.ajax({
    url: endereco,
    complete: function(res){
        var meuJSON = JSON.parse(res.responseText);
        console.log(meuJSON); 
    }
});

Demo live

A request / ajax call allows you to interact with the "server side". Thus client-side code can fetch information from a server. The same, or an exterior when it allows.

What you need to do is parse / convert the received data to a JSON object. Javascript has a native function for this, the JSON.parse ()

In this example I used jQuery, it is also possible with other libraries or even pure javascript.

    
26.03.2014 / 16:55
-1

That's what I was able to find answered SO English - >

You can do this like this:

function insertReply(content) {
    document.getElementById('output').innerHTML = content;
}

// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);

But source should be aware that you want it to call the function passed as callback parameter to it.

With the Google API it would look like this:

function insertReply(content) {
    document.getElementById('output').innerHTML = content;
}

// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);

Check out how the data looks like when you pass callback to the Google API:

link

Here is a very good explanation of JSONP: link

translated from: link

    
26.03.2014 / 15:57