导致 API 响应输出两次的 JavaScript 代码 [英] JavaScript code causing API response to output twice

查看:16
本文介绍了导致 API 响应输出两次的 JavaScript 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的 JavaScript 代码似乎可以正常工作,但只是返回的 API 响应输出出现了两次.我希望它只出现一次.

My JavaScript code below appears to be working but it is just that the returned API response output is appearing twice. I'd like it to appear only one time.

我的猜测可能是我对 success_callback 的错误使用,但我不确定如何修改它以使其正常工作.我也不确定我是向 API 发出两个请求,还是只是返回的响应获得两次输出的情况.

My guess is that perhaps it is my incorrect use of the success_callback, but I'm not sure how to modify that to get it to work properly. I'm also not sure if I'm making two requests to the API or if it's just a case where the returned response is getting output twice.

这是我的代码.这是什么原因造成的,我该如何纠正?

Here's my code. What's causing this and how do I correct it?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const Locations = require("./locations.js");

// Init API connector
var r = new API_Connector();

// Get the tour
r.tour(Locations.LOCATIONS, function(result) {

  // Success - Parse the data
  const parsedData = JSON.parse(result);

  // This loop steps through the JSON response and outputs the data           
  for (i = 0; i < parsedData.count; i++) {
    console.log(parsedData.route[i]);
  }

}, function(error) {
  // Error
  console.log(error);
});

function API_Connector() {
  this.tour = (_LOCATIONS, success_callback, error_callback) => {

    // Init the request object
    var httpRequest = new XMLHttpRequest();
    if (!httpRequest) {
      alert('Cannot create an XMLHttpRequest instance');
      return false;
    }

    var ulog = Buffer.from('username:password').toString('base64');

    // Set up the request and send it
    httpRequest.open('POST', "https://myapi.test.com/tour");
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.setRequestHeader("Authorization", "Basic " + ulog);

    var params = "locations=" + JSON.stringify(Locations.LOCATIONS);
    httpRequest.send(params);

    // Receive the response
    httpRequest.onreadystatechange = function() {

      if (httpRequest.status === 200) {
        success_callback(httpRequest.responseText);
        console.log('Success');
      } else {
        error_callback(httpRequest.responseText);
        console.log('No success');
      }
    };
  };
}

输出如下:

{ name: '40844, Home', arrival: 0, distance: 0 }
{ name: '40758, Purge', arrival: 44, distance: 55.3 }
{ name: '40810, Purge', arrival: 97, distance: 132.6 }
{ name: '40806, Purge', arrival: 180, distance: 253.6 }
{ name: '40804, Purge', arrival: 195, distance: 268.3 }
{ name: '40805, Purge', arrival: 232, distance: 317.6 }
{ name: '40861, Recycle', arrival: 290, distance: 400.5 }
Success
{ name: '40844, Home', arrival: 0, distance: 0 }
{ name: '40758, Purge', arrival: 44, distance: 55.3 }
{ name: '40810, Purge', arrival: 97, distance: 132.6 }
{ name: '40806, Purge', arrival: 180, distance: 253.6 }
{ name: '40804, Purge', arrival: 195, distance: 268.3 }
{ name: '40805, Purge', arrival: 232, distance: 317.6 }
{ name: '40861, Recycle', arrival: 290, distance: 400.5 }
Success

推荐答案

readystatechange 事件在 AJAX 请求的生命周期内发生多次.您需要检查 httpRequest.readyState 以判断您是否处于最终响应阶段.否则,您将多次调用 success_callback().

The readystatechange event occurs multiple times during the lifetime of an AJAX request. You need to check httpRequest.readyState to tell if you're at the final response stage. Otherwise you'll call success_callback() multiple times.

httpRequest.onreadystatechange = function() {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status === 200) {
      success_callback(httpRequest.responseText);
      console.log('Success');
    } else {
      error_callback(httpRequest.responseText);
      console.log('No success');
    }
  }
};

参见 XMLHttpRequest.readyState不同状态值的文档.

See XMLHttpRequest.readyState documentation for the different state values.

这篇关于导致 API 响应输出两次的 JavaScript 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆