繁体   English   中英

Javascript AJAX XMLHttpRequest

[英]Javascript AJAX XMLHttpRequest

我正在使用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();

我已经读了很多东西,但是无法按我的意愿去工作,请帮忙! 谢谢

简短答案:

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请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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