首页 > 解决方案 > 如何在 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));
}

标签: javascriptpythonajaxflaskflask-mongoengine

解决方案


如果在变量和字符串之间放置一个变量,则可以将变量添加到+字符串中。所以你不会这样做:

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至。


推荐阅读