简体   繁体   中英

How to pass data from json api to javascript var

Hello I need some help i am new learning so well the question might be a little silly but anyways I am tired of search everywhere and not able to find the answer I need.

So basically I have this json located at http://swapi.co/api/people/1/?format=json and I have this function in javascript:

function get_data_api()
{
 var data = anything_in_http://swapi.co/api/people/1/?format=json

 alert("name_of_json_from_url")
 }

So what I am trying to is to assign to that var data everything cotained in the json URL and then fetched to every tag and show them in an alert.

Hope it makes sense!

This is a JavaScript implementation you don't need JQuery

 var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function() { var readyState = xhr.readyState; var status = xhr.status; if (readyState == 4 && status == 200) { callback(null, xhr.response); } else { callback(status); } }; xhr.send(); }; getJSON('http://swapi.co/api/people/1/?format=json', function(err, data) { if (err != null) { alert('You have an error: ' + err); } else { console.log(data); alert('The name from the URL: ' + data.name); } }); 

You can use jQuery http://api.jquery.com/jquery.getjson/

var jqxhr = $.getJSON( "http://swapi.co/api/people/1/?format=json", function() {
  console.log( "success" );
})
  .done(function(data) {
    console.log( data.name );
});

This is a possible duplicate of How to get JSON from URL in Javascript? which is the first result on google with keyword "javascript json from url" maybe you were using a wrong keywords for searching

Extra info: How to add jQuery to your page Add inside html head <head> </head> the jQuery js file

Method 1: Use CDN hosted js file

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Method 2: Download jquery.min.js then

<script src="/path/in/your/server/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM