【问题标题】:Change parameters in HTTP web requests更改 HTTP Web 请求中的参数
【发布时间】:2020-10-08 05:04:08
【问题描述】:

大家好,我是 Web 开发的新手。我使用 fetch API 发送一个 http 请求,如下所示。它运作良好。但是现在我想在执行 sql 查询时更改第二个参数(即 IP 地址)。所以这个想法是每次我在网页上按下一个按钮时,都会在 IP 所在的地方执行 sql 查询。是否可以为 sql 查询设置一个变量并写入该变量来代替 IP?任何帮助表示赞赏。谢谢

 fetch("    http://192.xx.x.xxx/abc-bin/output?username=one&password=xxxx&action=on&pin=relay")
  .then(function (response) {
    return response.json();
  })

【问题讨论】:

  • 是的……你可以用字符串做各种各样的事情,而 fetch 中的 url 只是一个字符串——当然,你要如何在浏览器中“执行 sql”?
  • 执行 SQL 查询,然后在处理结果的回调函数中,将您从数据库中获取的 IP 连接到 URL 中。
  • 请注意,您实际上并没有在此处修改 SQL。您正在调整一个看起来像是在调用 REST API 的 HTTP 请求。服务器接收 HTTP 请求,解释它们并执行将代表您与数据库交互的代码,将 SQL 语言从交互中抽象出来

标签: javascript html web-development-server


【解决方案1】:

是的,这是 javascript 中非常常见的任务。你有很多选择来解决这个问题。您如何设置变量将取决于您的前端 javascript 点击处理程序或按钮本身的 html 属性。

选项 1 - 字符串连接

// Create a variable with the IP or Domain you would like to replace with
// If you didn't know domains are mapped to IPs, so you can use each inter-changably


// Example variables
const protocol = 'https://'
const domain = 'www.stackoverflow.com'
const path = '/abc-bin/output?username=one&password=xxxx&action=on&pin=relay'

// Concatinate to create single string
const url = protocol + domain + path

fetch(url)
  .then(function (response) {
    return response.json();
  })

选项 2 - 字符串插值

// Example variables
const domain = 'www.stackoverflow.com'

// Interpolate string...NOTE they aren't single quotes but 
// are backticks (top left key on US keyboard)
// You must wrap your variables with ${variableName} to
// have it interpreted as a string
const url = `https://${domain}/abc-bin/output?username=one&password=xxxx&action=on&pin=relay`

fetch(url)
  .then(function (response) {
    return response.json();
  })

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多