首页 > 解决方案 > 遍历js中的数组

问题描述

  var webhook_array = webhook_url.split(",");
  console.log(webhook_array);
  function send(item) {
    console.log(item)
    request.open("POST", item);
    request.setRequestHeader('Content-type', 'application/json');
  
    var myEmbed = {
      title: embed_title,
      color: hexToDecimal(hexcolour),
      description: message_content,
      footer: {
        text: "Powered by Yapplex Tools",
        icon_url: avatarurl,
      }
    }
    
    var params = {
      username: webhook_username,
      avatar_url: avatarurl,
      embeds: [ myEmbed ]
    }
    request.send(JSON.stringify(params));
  }
  webhook_array.forEach(send);

  function hexToDecimal(hex) {
    return parseInt(hex.replace("#",""), 16)
  }
}

此代码应通过数组中的每个 webhook 并使用它们发送消息。它将它们打印到控制台,这意味着它们在那里并且可以检测到它们,但只调用了一个 webhook(当使用两个 webhook 进行测试时)

标签: javascriptnode.jselectrondiscord

解决方案


有几件事可能会给您带来问题。最值得注意的是,您需要创建一个新的 XMLHttpRequest()。



  var webhook_array = webhook_url.split(",");
  console.log(webhook_array);
  function send(item) {
    console.log(item)

    /** CREATE REQUEST HERE */
    const request = new XMLHttpRequest();
    /** SHOULD WORK NOW */

    request.open("POST", item);
    request.setRequestHeader('Content-type', 'application/json');
  
    // Other code...
    request.send(JSON.stringify(params));
  }
  webhook_array.forEach(send);

您包含的示例还有一些未定义的变量(avatarurl, webhook_username)和一个额外的大括号。确保它们在您的代码中的其他地方:它们可能只是文件的一部分,没有出现在您的问题中。希望这可以帮助!


推荐阅读