簡體   English   中英

如何在 javascript fetch() 方法上傳遞帶有 url 的變量?

[英]How to pass a variable with url on javascript fetch() method?

我正在嘗試使用 javascript 上的 GET 方法從 URL 獲取數據,

      fetch('/api/staffattendance/{makedate}')
        .then(res => res.json())
        .then(res => {
          //this.staffs = res.data;
          console.log(res.data);
        })
        .catch(err => console.log(err));

我如何在這里傳遞變量

fetch('/api/staffattendance/{makedate}')

像這樣

在此處輸入圖片說明

提前致謝,

一種方法是字符串連接,但js引入了另一種稱為template literal機制:

用 `` 嵌入字符串,用 ${makedate} 嵌入用戶變量。

`/api/staffattendance/${makedate}`

如果這有幫助,請告訴我。

您還可以將字符串放在反引號 `` 中,並在您想要變量的位置包含${yourVariable} ,例如:

  fetch(`/api/staffattendance/${makedate}`)
    .then(res => res.json())
    .then(res => {
      //this.staffs = res.data;
      console.log(res.data);
    })
    .catch(err => console.log(err));

在 JavaScript 周圍使用${your-variable} ,您是否將整個 URL 包含在尖括號中(“1”鍵左側的這些小家伙)?

fetch('/api/staffattendance/'+makedate+'')

像這樣簡單地連接對我有用

暫無
暫無

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

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