简体   繁体   English

如何在 JavaScript 中的 POST 请求 URL 中传递变量?

[英]How do I pass a variable inside a POST request URL in JavaScript?

I am trying to pass a variable that is derived from a database (and keeps changing) to a fetch URL.我正在尝试将从数据库(并不断变化)派生的变量传递给提取 URL。 I don't want to hard code it in the URL.我不想在 URL 中对其进行硬编码。 How do I go about it?我该怎么做? Here is the snippet of the code.这是代码的片段。

  };
  var searchString = amount;
  var payload = JSON.stringify(data);
  var options = {
    'method': 'POST',
    'Content-Type': 'application/json', 
    'payload' : data,
  };
  var url = 'https://......./**amount**/budget_items?token';
  var response = UrlFetchApp.fetch(url, options);

I want to pass the search string variable but I don't know-how.我想传递搜索字符串变量,但我不知道如何。 Any help?有什么帮助吗?

If you want to include searchString in the url you can use string concatenation or string interpolation.如果您想在url包含searchString ,您可以使用字符串连接或字符串插值。 Here is string concatenation:这是字符串连接:

var url = 'https://.../' + searchString + '/...';

And here is string interpolation:这是字符串插值:

var url = `https://.../${searchString}/...`;

If you're sending a GET request, you must include the query arguments in the URL.如果您要发送GET请求,则必须在 URL 中包含查询参数。 You don't have to hardcode anything - just add the query parameters in the fetch itself:您不必对任何内容进行硬编码 - 只需在 fetch 本身中添加查询参数:

var response = UrlFetchApp.fetch(url + `?search=${searchString}`);

If you're trying to send a JSON object, you should instead use POST .如果您尝试发送JSON对象,则应改用POST You'll be able to preserve the URL as it is (as long as it's accepting POST requests).您将能够按原样保留 URL(只要它接受POST请求)。 You'll be able to send JSON in the data option too.您也可以在data选项中发送JSON

To dynamically include searchString in the URL string you can use Matt's method, but you have some problem with your code.要在 URL 字符串中动态包含searchString ,您可以使用 Matt 的方法,但是您的代码存在一些问题。 You are passing the wrong payload.您正在传递错误的有效载荷。 Here is the modified code you can use it.这是您可以使用的修改后的代码。

   };
  var searchString = amount;
  var payload = JSON.stringify(data);
  var options = {
    'method': 'POST',
    'Content-Type': 'application/json', 
    payload
  };
  var url = `https://......./${searchString}/budget_items?token`;
  var response = UrlFetchApp.fetch(url, options);

To know more about Template literals要了解有关模板文字的更多信息

You may also use URL object (needs polyfills in IE)你也可以使用URL对象(在 IE 中需要 polyfills)

const url = new URL('http://foo.bar/?search');
url.searchParams.set('search', searchString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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