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/

现在,"long answer",基本上你必须:

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

您还应该考虑开始使用 jQuery 或任何其他库来帮助您进行 DOM 操作和 AJAX 请求。