简体   繁体   中英

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

I'm trying to fetch data from URL with GET method on javascript,

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

How can I pass variable here

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

Like this

在此处输入图片说明

Thanks in Advance,

One method is the string concatenation but js has introduced another mechanism called template literal :

Embed the string with `` and user variable with ${makedate}.

`/api/staffattendance/${makedate}`

Let me know if this helps.

You can also put the string in backticks ``, and include ${yourVariable} where you want your variable, example:

  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+'')

像这样简单地连接对我有用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM