簡體   English   中英

GET API 對多個 URL 的請求

[英]GET API request to multiple URLs

問題:我有 47 個網址,所有網址的區別僅在於最后一個/兩個字符 1-47。

示例: https://example.com/api/data?number=1 <--- 最后一位數字范圍從 1 到 47

我需要向他們每個人發出 API GET 請求以獲取他們的數據,所以我可以 plot 他們。

到目前為止我所擁有的:

let exampleLink = 'https://example.com/api/data?code='

let data = []

const req = new XMLHttpRequest()

for(let i=1; i<48; i++){
  req.open('GET', exampleLink + i, true)
  req.send();

  req.onload = () => {
    let result = JSON.parse(req.responseText)
    data.push(result)
  }
}

這對我不起作用,FOR 循環最終只會給我最后一個結果 #47。

有誰知道如何提出這樣的請求並將響應數據推送到數組中?

非常感謝,

小程

有不同的方法可以解決這個問題。 在這種情況下,為了快速解決這個問題,您可以在 for 循環中使用局部變量,因為目前您每次都覆蓋請求。

let exampleLink = 'https://example.com/api/data?code='

let data = []

for(let i=1; i<48; i++){
  let req = new XMLHttpRequest()
  req.open('GET', exampleLink + i, true)
  req.send();

  req.onload = () => {
    let result = JSON.parse(req.responseText)
    data.push(result)
  }
}

它給你最后一個結果是正常的,你的代碼在 Javascript 中,嘗試使用異步 function,類似這樣的東西(axios 請求它是一個很棒的節點 ZEFE90A8E604A7C840E88D03A67F6 你應該看看它):

for(let i=1; i<48; i++){
source = url +`&page_size=${i}`
async function ResourcesFetcher() {
await axios.get(source).then((results ) => {
//the do whatever action you want to 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM