我使用Javascript来读取服务器响应,我希望过滤服务器提供的信息,这样我就可以在页面上对其进行样式设置。提供了以下api调用:
http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json并检索此信息:
{"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",...}我需要过滤来自该响应的信息,以只显示标题和运行时信息
<p id="Title">Movie title!</p>
<p id="Runtime">Movie runtime!</p>对api的调用是:
xhttp.open("GET", "http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json"+str, true);
xhttp.send();我读了很多东西,但不能按我的意愿去工作,我会得到一些帮助!谢谢
发布于 2016-03-24 01:33:18
简短答覆:
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);运行示例:https://jsfiddle.net/mgjyv3q6/1/
现在,“长话短说”,基本上你必须:
response或responseText解析为JSON。此外,您应该考虑开始使用jQuery或任何其他库来帮助您处理DOM操作和AJAX请求。
https://stackoverflow.com/questions/36191649
复制相似问题