javascript - 如何在 fetch Api 命令中添加局部变量
问题描述
我想在我的 fetch 命令中传递这些参数,以便将这些信息保存在我的数据库中
function addItemToCart(title,price,imgSrc)
{
console.log('starting ajax call')
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("http://127.0.0.1:5000/query?product=title", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
解决方案
如果在变量和字符串之间放置一个变量,则可以将变量添加到+
字符串中。所以你不会这样做:
var url = 'http://127.0.0.1:5000/query?product=' + title;
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(url, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
然后,您可以让 Flask 使用以下代码行解析结果:
# Top
from flask import request
# View code
title = request.args.get('product')
希望这可以帮助
附言。请记住,在执行 args.get 时,字符串应该是 url 中的“变量”,所以如果您要查找 id,那么您应该说www.url.com?id=15
,但如果您愿意,可以使用任何单词而不是 id至。
推荐阅读
- laravel - Laravel 获取 JSON 列 MariaDB 语法错误
- css - 无法以角度获取openlayers css
- linux - 如何查找具有特定名称的所有子目录并删除其内容(而不是删除目录本身)
- coq - Coq 中的 b/w 等变和协变箭头有什么区别?
- amazon-web-services - 带参数的 appsync 订阅
- django - 在服务器私有 IP/vpn 隧道上访问 Django 应用程序
- loopbackjs - tp 如何从 loopback.js 远程方法发送大数据集
- ruby - 如何过滤对象数组
- tensorflow - GPU 中的 Bfloat16 训练
- python - 如何在 Python 中显示数字的最后 2 位数字