Im using Javascript to read on a server response and i want to filter the information given by the server so i can style it on my page. The following api call is presented:
http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json
And retrieves this information:
{"Title":"Pulp Fiction","Year":"1994","Rated":"R","Released":"14 Oct 1994",
"Runtime":"154 min","Genre":"Crime, Drama","Director":"Quentin Tarantino",
"Writer":"Quentin Tarantino (story), Roger Avary (story), Quentin Tarantino",
"Actors":"Tim Roth, Laura Lovelace, John Travolta, Samuel L. Jackson",...}
I need to filter the information from that response to only show the Title and the Runtime information
<p id="Title">Movie title!</p>
<p id="Runtime">Movie runtime!</p>
The call to the api is:
xhttp.open("GET", "http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json"+str, true);
xhttp.send();
I have read lots of things but cant get it to work as i want to, ill apreciate some help! Thanks
Short answer:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
// Step 1 below
var fullMovie = JSON.parse(xhr.responseText);
// Step 2 below
var movie = { title: fullMovie.Title, runtime: fullMovie.Runtime };
// Step 3 below
document.getElementById('Title').innerText = movie.title;
document.getElementById('Runtime').innerText = movie.runtime;
}
}
xhr.open('GET', 'http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json', true);
xhr.send(null);
Running sample: https://jsfiddle.net/mgjyv3q6/1/
Now, "long answer", basically you have to:
response
or responseText
as JSON. Also you should consider start using jQuery or any other library to help you with DOM manipulation and AJAX requests.
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.