I try to call API from swapi, I need to show title of films. I using jQuery to create it
here is my javascript
$(function(){
function promiseTest(){
return $.ajax({
type: 'GET',
url: 'https://swapi.co/api/people/',
})
}
function promiseTest2(){
return $.ajax({
type: 'GET',
url: 'https://swapi.co/api/films/',
})
}
var promise = promiseTest();
var promise2 = promiseTest2();
var bothPromise = $.when(promise, promise2);
bothPromise.done(function(data){
$.each(data, function(i, name){
$("#app").append("<ul><li>Name: "+ i.name +"</li><li>Height: "+name.height+" </li><li>Skin Color: "+ name.skin_color +"</li><li>Gender: "+name.gender+" </li><li>Film: "+ name.films.title +"</ul>")
})
})
HTML:
<div id="app"></div>
Here is my full code http://jsfiddle.net/dedi_wibisono17/phq7t50u/2/
I has try like this code , but I want to show the title of films from https://swapi.co/api/films/ .
Anybody help? Thank you
data[0].results
- it doesn't exist in the base data
. .each
, the first argument is the iteration number , not the item being iterated over. Give the function a second argument, and use it when specifying the names, heights, etc of the people: function promiseTest() { return $.ajax({ type: 'GET', url: 'https://swapi.co/api/people/', }) } function promiseTest2() { return $.ajax({ type: 'GET', url: 'https://swapi.co/api/films/', }) } var promise = promiseTest(); var promise2 = promiseTest2(); var bothPromise = $.when(promise, promise2); bothPromise.done(function(data) { $.each(data[0].results, function(i, e) { $("#app").append("<ul><li>Name: " + e.name + "</li><li>Height: " + e.height + " </li><li>Skin Color: " + e.skin_color + "</li><li>Gender: " + e.gender + " </li><li>Film: " + e.films + "</ul>") }) /*alert("done")*/ })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div>
But there's no need for jQuery at all just for this - you can use fetch
and Promise.all
, which are supported natively in non-ancient browsers:
Promise.all([ fetch('https://swapi.co/api/people/').then(res => res.json()), fetch('https://swapi.co/api/films/').then(res => res.json()) ]).then(data => { const app = document.querySelector('#app'); data[0].results.forEach((e) => { app.innerHTML += "<ul><li>Name: " + e.name + "</li><li>Height: " + e.height + " </li><li>Skin Color: " + e.skin_color + "</li><li>Gender: " + e.gender + " </li><li>Film: " + e.films + "</ul>" }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div>
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.