首页
学习
活动
专区
圈层
工具
发布

Javascript
EN

Stack Overflow用户
提问于 2016-03-24 01:19:20
回答 1查看 112关注 0票数 0

我使用Javascript来读取服务器响应,我希望过滤服务器提供的信息,这样我就可以在页面上对其进行样式设置。提供了以下api调用:

代码语言:javascript
复制
http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json

并检索此信息:

代码语言:javascript
复制
{"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",...}

我需要过滤来自该响应的信息,以只显示标题和运行时信息

代码语言:javascript
复制
<p id="Title">Movie title!</p>
<p id="Runtime">Movie runtime!</p>

对api的调用是:

代码语言:javascript
复制
xhttp.open("GET", "http://www.omdbapi.com/?t=pulp+fiction&y=&plot=short&r=json"+str, true);
xhttp.send();

我读了很多东西,但不能按我的意愿去工作,我会得到一些帮助!谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-24 01:33:18

简短答覆:

代码语言:javascript
复制
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/

现在,“长话短说”,基本上你必须:

  1. responseresponseText解析为JSON。
  2. 使用所需的字段创建一个新对象。
  3. 在UI中呈现检索到的信息。

此外,您应该考虑开始使用jQuery或任何其他库来帮助您处理DOM操作和AJAX请求。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36191649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档